简体   繁体   English

如何按不同条件过滤列表?

[英]How can I filter a list by different conditions?

I've written the following code: 我编写了以下代码:

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)

The problem is that this returns a list of numbers that satisfy at least one of the 3 conditions. 问题在于,这将返回至少满足3个条件之一的数字列表。

The result I want is a list of the numbers that satisfy all three conditions. 我想要的结果是满足所有三个条件的数字的列表。 How could I achieve that? 我该如何实现?

Use a single if statement that combines all your conditions 使用一个包含所有条件的if语句

if element<0 and element%9==0 and element%2!=0 :
    list2.append(element)

尝试列表理解:

list_2 = [i for i in list_1 if i<0 and i%9==0 and i%2 !=0]

您还可以使用函数filter()&代替AND|代替OR ):

list(filter(lambda x: x < 0 & x % 9 == 0 & x % 2 != 0, list_1)

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

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