假设我有一个列表
my_list = ['91 9925479326','18002561245','All the best','good']
现在我想忽略列表中以91
和18
开头的字符串,如下所示:
result = []
for i in my_list:
if not '91' in i:
if not '18' in i:
result.append(i)
所以我想用列表推导式来实现这个。
在列表推导式中有没有办法写两个 if 条件?
[i for i in my_list if '91' not in i and '18' not in i]
请注意,您不应将list
用作变量名,它会隐藏内置函数。
startswith
而不是 in
来检查值。 - Igor Chubin现在我想忽略列表中以91和18开头的字符串,如下所示
- Igor Chubin如果你有超过两个值(例如91和18),或者它们是动态产生的,使用以下结构会更好:
[i for i in my_list if not i.startswith(('91', '18'))]
如果你想检查字符串中是否包含 91
和 18
(不仅在开头),请使用in
而不是startswith
:
[i for i in my_list if all(x not in i for x in ['91', '18'])]
使用示例:
>>> my_list = ['91 9925479326','18002561245','All the best','good']
>>> [i for i in my_list if all(not i.startswith(x) for x in ['91', '18'])]
['All the best', 'good']
>>>
[i for i in my_list if not any(i.startswith(x) for x in ['91', '18'])]
但我想这是个人偏好。 - jamylak.startswith
还可以接受一个字符串元组,因此可以缩短为 [i for i in my_list if not i.startswith(('91', '18'))]
。 - MRABif ((not '91' in i) and (not '18' in i))
DeMorgan's Law
,可以将其转化为:如果i
中既没有包含字符串'91'
也没有包含字符串'18'
。使用DeMorgan's Law
,可以将其简化为:如果'91'
和'18'
都不在i
中。 - Blckknght
91
和18
,无论它们在哪个位置。你应该改用str.startswith
:http://docs.python.org/library/stdtypes.html#str.startswith - Giulio Piancastelli