我的问题是关于eval()包含可信用户输入的字符串。我不确定如何正确打包字符串(尝试后的第一行:)。在下面的示例中,eval()引发了异常。任何帮助将受到高度赞赏。这是一个示例代码:
import ast
def do_set_operation_on_testids_file(str_filename1, str_filename2, str_set_operation):
resulting_set = None
with open(str_filename1) as fid1:
with open(str_filename2) as fid2:
list1 = fid1.readlines()
list2 = fid2.readlines()
try:
str_complete_command = "set(list1)." + str_set_operation + "(set(list2))"
resulting_set = ast.literal_eval(str_complete_command)
for each_line in resulting_set:
print(each_line.strip().strip('\n'))
except:
print('Invalid set operation provided: ' + str_set_operation)
非常感谢!
答案 0 :(得分:2)
您根本不需要使用literal_eval()
或eval()
。
使用getattr()
通过字符串获取set操作方法:
>>> list1 = [1,2,3,2,4]
>>> list2 = [2,4,5,4]
>>> str_set_operation = "intersection"
>>> set1 = set(list1)
>>> set2 = set(list2)
>>> getattr(set1, str_set_operation)(set2)
set([2, 4])
或者,您可以传递operator
函数而不是带有set方法名称的字符串。例如:
>>> import operator
>>> def do_set_operation_on_sets(set1, set2, f):
... return f(set1, set2)
...
>>> do_set_operation_on_sets(set1, set2, operator.and_)
set([2, 4])
其中and_
会调用set1 & set2
,这是集合的交集。