我有一个字符串列表
["oranges", "POTATOES", "Pencils", "PAper"]
我想查找列表中是否包含paper
,忽略大小写;所以下面的代码片段应该打印 found
。我的列表仅包含仅由英文字母组成的简单字符串——大写和小写。
item = 'paper'
stuff = ["oranges", "POTATOES", "Pencils", "PAper"]
if item in stuff:
print "found"
else:
print "Not found"
#How do I get the method to print "found"?
澄清:
我的列表实际上是列表的列表,我的逻辑使用以下结构:
if not any ( item in x for x in stuff):
print "Not found"
else:
print "found"
最佳答案
我会将 lower
与 any
结合起来:
>>> stuff = ["oranges", "POTATOES", "Pencils", "PAper"]
>>> any(s.lower() == 'paper' for s in stuff)
True
>>> any(s.lower() == 'paperclip' for s in stuff)
False
这将短路并在找到一个时立即停止搜索(与 listcomp 不同)。 OTOH,如果您要进行多次搜索,那么您不妨使用 listcomp 来降低整个列表一次。
对于您更新的案例(为什么从来没有人问他们感兴趣的问题,而是问一个不同的问题?),我可能会做类似的事情
>>> any("book" in (s.lower() for s in x) for x in stuff)
True
>>> any("paper" in (s.lower() for s in x) for x in stuff)
True
>>> any("stuff" in (s.lower() for s in x) for x in stuff)
False
同样的规则也适用。如果您要进行多次搜索,最好将列表的列表规范化一次。
关于 python 2.7 : find item in list ignoring case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13809299/