简体   繁体   English

python的不区分大小写的IN

[英]Case-insensitive IN for python

Is there a way to do a SQL-like IN statement in python. 有没有办法在python中做类似SQL的IN语句。 For example: 例如:

'hello' in ['Hello', 'Goodbye'] # case insensitive
True

I was thinking a list comprehension to rebuild the list, but hopefully there is something much simpler. 我本以为可以通过列表理解来重建列表,但是希望可以更简单一些。

You can map the list to str.lower : 您可以将列表mapstr.lower

if 'hello' in map(str.lower, ['Hello', 'Goodbye']):

In Python 3.x, this will not build a new list since map returns an iterator. 在Python 3.x中,由于map返回迭代器,因此不会建立新列表。 In Python 2.x, you can achieve the same by importing itertools.imap . 在Python 2.x中,可以通过导入itertools.imap实现相同的目的。


Alternately, you could just use a generator expression : 或者,您可以只使用一个生成器表达式

if 'hello' in (x.lower() for x in ['Hello', 'Goodbye']):

This is lazy too and works the same in both versions. 这也很懒,并且在两个版本中都相同。

A generator expression using any would be one of the more efficient ways, it will lazily evaluate short circuiting if we find a match: 使用any的生成器表达式将是更有效的方法之一,如果找到匹配项,它将懒惰地评估短路:

l =['Hello', 'Goodbye'] 
s = "hello"
if any(s == x.lower() for x in l):
    ....

In [10]: l =['Hello', 'Goodbye']   
In [11]: s = "hello"    
In [12]: any(s == x.lower() for x in l)
Out[12]: True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM