a = [0,1,2,3,4,5,6]
for x in a:
list(x < 4):
预期输出:[0,1,2,3]
实际输出:[True, True, True, True, False, False, False]
知道如何得到我想要的东西吗?
答案 0 :(得分:8)
答案 1 :(得分:5)
您可以使用filter
:
>>> a = [0,1,2,3,4,5,6]
>>> list(filter(lambda x: x < 4, a))
[0, 1, 2, 3]
或itertools.takewhile
(如果列表已排序):
>>> from itertools import takewhile
>>> a = [0,1,2,3,4,5,6]
>>> list(takewhile(lambda x: x < 4, a))
[0, 1, 2, 3]