Python 2.7:在列表中查找项忽略cas

2024-06-16 11:42:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串列表

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

Tags: 字符串in列表ifnotitemelsepaper
3条回答

可以使用List Comprehension将列表转换为小写。

if item in [x.lower() for x in stuff]:
    print "found"
else:
    print "not found"

stuff = ["oranges", "POTATOES", "Pencils", "PAper"]
print [x.lower() for x in stuff]
['oranges', 'potatoes', 'pencils', 'paper']

我会把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)。哦,如果你要进行多个搜索,那么你最好使用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

不过,同样的规则也适用。如果您正在执行多个搜索,那么最好将列表列表规范化一次。

将两个字符串转换为大写或小写并进行比较?

item = 'paper'
stuff = ["oranges", "POTATOES", "Pencils", "PAper"]
if item.upper() in map(lambda x: x.upper(), stuff):
    print "found"
else:
    print "Not found"

额外: 那就用这条线

if not any ( item.upper() in map(lambda y: y.upper(), x) for x in stuff):

相关问题 更多 >