通过少于生成列表python运行列表

时间:2016-02-23 23:20:27

标签: python

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]

知道如何得到我想要的东西吗?

2 个答案:

答案 0 :(得分:8)

a = [0,1,2,3,4,5,6]
print ([x for x in a if x<4])

输出;

[0, 1, 2, 3]
>>> 

评论后编辑:它名为list comprehension

答案 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]