[英]In python how can I set multiple values of a list to zero simultaneously?
Conceptually, I want to do: 从概念上讲,我想这样做:
arr[20:] = 0
where arr
is a list
. 其中arr
是list
。 How can I do this? 我怎样才能做到这一点?
You can do it directly using slice assignment. 您可以使用切片分配直接进行操作。
arr[20:] = [0] * (len(arr) - 20)
But the natural way is just to iterate. 但是自然的方法只是迭代。
for i in xrange(20, len(arr)):
arr[i] = 0
Here are a couple of options: 这里有几个选择:
List comprehension 清单理解
>>> a = [1]*50
>>> a = [aa if i < 20 else 0 for i,aa in enumerate(a)]
>>> a
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
List slice assignment: 列表切片分配:
>>> a = [1]*50
>>> a[20:] = [0 for aa in a[20:]]
>>> a
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Zip(*zip): 邮编(* zip):
>>> a = [1]*50
>>> a[20:] = zip(*zip(a[20:],itertools.repeat(0)))[1]
arr.fill(0)
numpy.ndarray.fill()将用标量值填充ndarray
If you use list comprehension you make a copy of the list, so there is memory waste. 如果使用列表推导,则会复制列表,因此会浪费内存。 Use list comprehension or slicing to make new lists, use for cicles to set your list items correctly. 使用列表理解或切片来创建新列表,使用cicle可以正确设置列表项。
You can make a function that you will pass the array to that will zero out the array. 您可以创建一个函数,将数组传递给该函数,以使该数组归零。 I haven't used Python in a while, so I won't attempt to show you the Python code. 我已经有一段时间没有使用Python了,所以我不会尝试向您展示Python代码。 In that function you could use a for
or while
loop to iterate through each value and setting each one equal to zero. 在该函数中,您可以使用for
或while
循环迭代每个值,并将每个值设置为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.