在python中查看满足哪个条件的好方法

问题描述 投票:0回答:2

我有三个不同的if conditions,想要了解哪些条件得到满足。

我以为我可以使用空列表来处理它,如果条件满足则追加1,否则为0。

check_list = []
sample = [1,4,7]
fixed_number = 5

if sample[0] < fixed_number:
    check_list.append(1)
else:
    check_list.append(0)

if sample[1] < fixed_number:
    check_list.append(1)
else:
    check_list.append(0)

if sample[2] < fixed_number:
    check_list.append(1)
else:
    check_list.append(0)


check_list

在这种情况下所需的输出:

[1,1,0]

如何使这段代码简短而pythonic?

谢谢。

python if-statement condition
2个回答
2
投票

这个:

check_list = [s < fixed_number for s in sample]

如果你真的关心0和1,请使用int(s < fixed_number)


1
投票
check_list = []
sample = [1, 4, 7]
fixed_number = 5

for i in sample:
    if i < fixed_number:
        check_list.append(1)
    else:
        check_list.append(0)

print(check_list)

您可以使用循环一次检查条件,而不是每次都调用。

© www.soinside.com 2019 - 2024. All rights reserved.