如何按不同条件筛选列表?
How can I filter a list by different conditions?
我写了下面的代码:
list_1 = [5, 18, 3]
list_2 = []
for element in list_1:
if element < 0:
list_2.append(element)
elif element % 9 == 0:
list_2.append(element)
elif element % 2 != 0:
list_2.append(element)
else:
print('No number is valid')
print(list_2)
问题是这个 returns 至少满足 3 个条件之一的数字列表。
我想要的结果是满足所有三个条件的数字列表。我怎样才能做到这一点?
尝试列表理解:
list_2 = [i for i in list_1 if i<0 and i%9==0 and i%2 !=0]
使用一个结合所有条件的 if 语句
if element<0 and element%9==0 and element%2!=0 :
list2.append(element)
您还可以使用函数 filter()
和 &
代替 AND
(|
代替 OR
):
list(filter(lambda x: x < 0 & x % 9 == 0 & x % 2 != 0, list_1)
我写了下面的代码:
list_1 = [5, 18, 3]
list_2 = []
for element in list_1:
if element < 0:
list_2.append(element)
elif element % 9 == 0:
list_2.append(element)
elif element % 2 != 0:
list_2.append(element)
else:
print('No number is valid')
print(list_2)
问题是这个 returns 至少满足 3 个条件之一的数字列表。
我想要的结果是满足所有三个条件的数字列表。我怎样才能做到这一点?
尝试列表理解:
list_2 = [i for i in list_1 if i<0 and i%9==0 and i%2 !=0]
使用一个结合所有条件的 if 语句
if element<0 and element%9==0 and element%2!=0 :
list2.append(element)
您还可以使用函数 filter()
和 &
代替 AND
(|
代替 OR
):
list(filter(lambda x: x < 0 & x % 9 == 0 & x % 2 != 0, list_1)