简体   繁体   English

在python中如何将列表的多个值同时设置为零?

[英]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 . 其中arrlist 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. 在该函数中,您可以使用forwhile循环迭代每个值,并将每个值设置为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据索引同时从 Python 中的列表中删除多个值? - How to simultaneously delete multiple values from a list in Python based on their index? 如何在python中使用opencv同时播放多个视频? - how can I play multiple videos simultaneously using opencv in python? 如何在 Python dataframe 中同时替换多行? - How can I replace multiple rows simultaneously in a Python dataframe? 我可以同时在Python中运行多个计时器吗? - Can I run multiple Timers in Python simultaneously? Python:如何将list / array / pd.Series中的零值设置为下一个非零值? - Python: How to set values of zero in a list/array/pd.Series to be the next non-zero value? 如何在列表中插入多个值? (Python) - How can I insert multiple values into a list? (python) Python - 初学者帮助 - 如何将 append 多个值添加到一个列表中? - Python - beginner help - How can I append multiple values to a list? 同时将字典的所有值替换为零 python - Simultaneously replacing all values of a dictionary to zero python 如何在 python 列表的空位中添加零? - How can I add zero's in empty slots in a list in python? 如何使用列表同时从包/模块中调用多个方法/属性 - How can I call multiple methods/attributes from a package/module simultaneously using a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM