python 2.7 : find item in list ignoring case

标签 python 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"

最佳答案

我会将 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/

相关文章:

python - 选择文件夹中最大的文件而不是在 Python 中应用几个函数

python - 如何以及何时在 Python 中适本地使用弱引用

python - 用 python 中相应的名称替换数千行 ID 名称的最佳方法是什么?

python - Numpy savez 异常

python - 网格未按预期工作 python Tkinter

python - 在 Python 中从字符串中拆分数字

python-2.7 - 在 Windows 7 64 位上安装 numpy、matplotlib

python - 如何在 Mac OSX 下安装 ijson python 包(find_library 问题?)

python - Python 函数调用中的条件参数

python - 类型错误 : unsupported operand type(s) for ^: 'numpy.float64' and 'numpy.float64'