gpt4 book ai didi

python 2.7 : find item in list ignoring case

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:31 24 4
gpt4 key购买 nike

我有一个字符串列表

["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"

最佳答案

我会将 lowerany 结合起来:

>>> 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com