我有一个各种类型的Python文字列表,例如:
literals = [1, 2, 'a', False]我所说的“文字”是指任何可以是ast.literal_eval输出的Python对象。我想编写一个函数literalInList来检查literals列表中是否有其他的Python文字x:
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)诚然,对于一个简单的任务来说,这是相当丑陋的。有没有一种更优雅、更高效或更毕达通的方式?
发布于 2019-07-10 18:52:58
以下几点如何?
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)) # Falsehttps://stackoverflow.com/questions/56976737
复制相似问题