2012-12-10 28 views
0

我有一个字符串列表的Python 2.7:找到列表项忽略大小写

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

回答

13

我会结合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 

同样的规则虽然如此。如果您正在进行多次搜索,那么您最好将列表列表规范化一次。

+0

后,他贴在编辑的代码我忍不住票... – squiguy

+0

谢谢你这么多为优雅的回应! – kasavbere

0

而不是使用你现在有什么,你可以使用lower功能。

for strings in stuff: 
    if strings.lower() == item: 
    print "found" 

print "Not found" 
1

将两个字符串转换为大写还是小写并比较它们?

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): 
2

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

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

东西= [ “桔子”, “土豆”, “铅笔”, “纸”]
打印[x.lower()对于x在东西]
[ '桔子', '土豆', '铅笔', '纸']

1

不是蟒蛇爱好者和一般的新的节目,但是好了,这里是我的解决方案:

我试图贴近您的一般方法,但是你可能想寻找到一个函数中封装代码。

我不知道你的水平经验,所以请原谅,如果我张贴的东西,你已经熟悉

这里上的功能的一般信息: wikipedia

这里蟒蛇文档在功能: Python Documentation

首先解决方案,冗长,但新的人本更容易理解:

def item_finder_a(item, stuff): 
    new_array = [] 
    for w in stuff: 
     new_array.append(w.lower()) 
    if item in new_array: 
     print "found" 
    else: 
     print "Not found" 

item_finder(word,array_of_words) 

而略短更简洁的版本

def item_finder_b(item, stuff): 
    if item in map(str.lower,stuff): 
     print "found" 
    else: 
     print "Not found" 

item_finder_b(word,array_of_words) 

希望这有助于

干杯