我该怎么做才能检查列表中的每个元素是否与Python中的某个条件匹配

时间:2017-10-28 20:06:01

标签: python python-2.7

如果我有一个列表:

nums = [1,2,3,4,5]

我希望得到如下结果:

whether_greater_than_two = [False, False, True, True, True]

在R中,我可以轻松应用nums > 2来获得上述结果。但是我应该在Python 2.7中做些什么呢?如果我再次使用nums > 2,我只会获得一个False

谢谢你们!

5 个答案:

答案 0 :(得分:3)

使用列表理解,正如其他人已经表明的那样。如果您真的关心性能,请改用 numpy arrays

>>> import numpy
>>> na = numpy.array([1,2,3,4,5])
>>> na > 2
array([False, False,  True,  True,  True], dtype=bool)
>>>

如果您来自R背景,很可能至少已经安装了 numpy matplotlib (可能还有很多其他数据分析) Python中的相关包)

答案 1 :(得分:2)

您可以构建列表理解:

nums = [1,2,3,4,5]
over_two = [num > 2 for num in nums]

输出:

[False, False, True, True, True]

答案 2 :(得分:2)

你可以这样做:

whether_greater_than_two = [ i>2 for i in nums ]

答案 3 :(得分:1)

你可以通过几种方式实现,最受欢迎的两种方式可能是列表理解和地图:

列表理解

whether_greater_than_two = [x > 2 for x in nums] 

地图

whether_greater_than_two = map(lambda x: x > 2, nums) 

请注意,在Python 3中,map会返回一个可以迭代的对象,但是如果你想要一个列表,你必须用list()调用来包装它:

list(map(lambda x: x > 2, nums))

当然,你可以用一个好老...

for循环

result = []
for x in nums:
    result.append(x > 2)

答案 4 :(得分:0)

map(lambda num: num > 2, nums)

[num > 2 for num in nums]

同时检查numpy,它提供了这种计算的快捷方式,并且比普通的python更快。