Python:使用eval函数

>>最全面的Java面试大纲及答案解析(建议收藏)  

这两天在hackerrank上刷题玩(其实到目前为止只看了8题),遇到一个需要处理输入并转化为对列表的处理操作的题。
原文:

Consider a list (list = []). You can perform the following commands:
   insert i e: Insert integer at position .
   print: Print the list.
   remove e: Delete the first occurrence of integer .
   append e: Insert integer at the end of the list.
   sort: Sort the list.
   pop: Pop the last element from the list.
   reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format
The first line contains an integer, , denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Constraints
   The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

题目大致是需要创建一个列表,接着获取键盘输入一个int类型的数N,并将这之后的N行输入视为对列表操作的指令。
实际代码如下:

 1if __name__ == '__main__':
2    N = int(input())
3    list = []
4    for i in range(N):
5        arg = input().split()
6        if len(arg) == 3:
7            eval("list." + arg[0] + "(" + arg[1] + "," + arg[2] + ")")
8        elif len(arg) == 2:
9            eval("list." + arg[0] + "(" + arg[1] + ")")
10        elif arg[0] == "print":
11            print(list)
12        else:
13            eval("list." + arg[0] + "()")

首先我们通过输入N确定了获取后续输入的循环次数,接着使用split方法将键盘输入变为字符串列表,通过观察我们发现,题目中输入的“命令”其实只有几种情况:三段字符串、两段、一段、以及特殊的print,并且全都与操作列表的方法名一致。
通过eval()函数,我们可以轻松的把这些字符串变为实际的方法。该函数将字符串当做有效的表达式运算并返回结果。

通过if判断,我们将不同的输入转换为对列表相应的操作。


原文始发于微信公众号(公子政的宅日常):Python:使用eval函数