我有各种类型的Python文字的列表,例如:
literals = [1, 2, 'a', False]
“文字”是指可以作为ast.literal_eval
输出的任何Python对象。我想编写一个函数literalInList
来检查x
列表中是否还有其他Python文字literals
:
x = True
if literalInList(x, literals): # Should be False.
print('The literal is in the list.')
请注意,我不能只做x in literals
,因为==
和in
运算符不会检查文字类型:
>>> True == 1
True
>>> False == 0
True
>>> 1 == 1.0
True
>>> True in [1, 2, 'a', False]
True
因此,我的最佳尝试是:
def literalInList(x, literals):
return any(x is lit for lit in literals)
对于一个听起来简单的任务,这确实很丑陋。有没有更优雅,有效或Pythonic的方式?
答案 0 :(得分:2)
以下内容如何:
def literalInList(x, literals):
def eq_x(y):
return x == y and type(x) is type(y)
return any(eq_x(y) for y in literals)
literals = [1, 2, 'a', False]
print(literalInList(True, literals)) # False
print(literalInList(False, literals)) # True
print(literalInList(1, literals)) # True
print(literalInList(1.0, literals)) # False