Skip to main content
 首页 » 编程设计

python之python 的不区分大小写的 IN

2025年05月04日11lexus

有没有办法在 python 中执行类似 SQL 的 IN 语句。例如:

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

我在想一个列表理解来重建列表,但希望有更简单的东西。

请您参考如下方法:

您可以 map str.lower 的列表:

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

在 Python 3.x 中,这不会构建新列表,因为 map 返回一个迭代器。在 Python 2.x 中,您可以通过导入 itertools.imap 来实现相同的目的.


或者,您可以只使用 generator expression :

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

这也很懒惰,并且在两个版本中工作相同。