[英]List of non-zero elements in a list in Python
Given the list 鉴于清单
a = [6, 3, 0, 0, 1, 0]
What is the best way in Python to return the list Python返回列表的最佳方法是什么
b = [1, 1, 0, 0, 1, 0]
where the 1's in b correspond to the non-zero elements in a. 其中b中的1对应于a中的非零元素。 I can think of running a for loop and simply appending onto b, but I'm sure there must be a better way. 我可以考虑运行for循环并简单地附加到b上,但我确信必须有更好的方法。
List comprehension method: 列表理解方法:
a = [6, 3, 0, 0, 1, 0]
b = [1 if i else 0 for i in a]
print b
>>>
[1, 1, 0, 0, 1, 0]
Timing mine, Dave's method and Lattyware's slight alteration : 我的时间, 戴夫的方法和Lattyware的轻微改动 :
$ python3 -m timeit -s "a = [6, 3, 0, 0, 1, 0]" "[1 if i else 0 for i in a]"
1000000 loops, best of 3: 0.838 usec per loop
$ python3 -m timeit -s "a = [6, 3, 0, 0, 1, 0]" "[int(i != 0) for i in a]"
100000 loops, best of 3: 2.15 usec per loop
$ python3 -m timeit -s "a = [6, 3, 0, 0, 1, 0]" "[i != 0 for i in a]"
1000000 loops, best of 3: 0.794 usec per loop
Looks like my method is twice as fast ... I am actually surprised it is that much faster. 貌似我的方法是快两倍......其实我惊奇地发现这是更快了 。 Taking out the int()
call, however, makes the two essentially the same - but leaves the resulting list full of Booleans
instead of Integers
(True/False instead of 1/0) 但是,取出int()
调用会使两者基本相同 - 但会使结果列表中的Booleans
而不是Integers
(True / False而不是1/0)
b = [int(i != 0) for i in a]
会给你你想要的东西。
For completeness, and since no one else added this answer: 为了完整性,并且因为没有其他人添加这个答案:
b = map(bool, a)
But it returns Boolean values and not Integers. 但它返回布尔值而不是整数。
How about 怎么样
>>> a = [6, 3, 0, 0, 1, 0]
>>> [bool(x) for x in a]
[True, True, False, False, True, False]
>>> [int(bool(x)) for x in a]
[1, 1, 0, 0, 1, 0]
Depending what you want it for, you might be better with the boolean list. 根据您的需要,使用布尔列表可能会更好。
Another way 其他方式
>>> a = [6, 3, 0, 0, 1, 0]
>>> [cmp(x,0) for x in a]
[1, 1, 0, 0, 1, 0]
Note that cmp(x,0)
returns -1 for negative numbers, so you might want to abs
that. 请注意,对于负数, cmp(x,0)
返回-1,因此您可能想要abs
。
You can also, depending on your application, work with numpy array representation: 您还可以根据应用程序使用numpy数组表示:
$ import numpy as np
$ a = [6, 3, 0, 0, 1, 0]
$ (np.array(a)!= 0).astype(int)
array([1, 1, 0, 0, 1, 0])
astype(int) is only necessary if you dont't want a boolean representation 只有在你不想要一个布尔表示时才需要astype(int)
而对于它来说,另一种方式:
[{0: 0}.get (el, 1) for el in your_list]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.