In python how can I set multiple values of a list to zero simultaneously?

前端 未结 5 1146
南旧
南旧 2021-02-04 02:10

Conceptually, I want to do:

arr[20:] = 0

where arr is a list. How can I do this?

相关标签:
5条回答
  • 2021-02-04 03:03

    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. In that function you could use a for or while loop to iterate through each value and setting each one equal to zero.

    0 讨论(0)
  • 2021-02-04 03:05

    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.

    0 讨论(0)
  • 2021-02-04 03:12
    arr.fill(0)
    

    numpy.ndarray.fill() will fill ndarray with scalar value

    0 讨论(0)
  • 2021-02-04 03:14

    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
    
    0 讨论(0)
  • 2021-02-04 03:14

    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):

    >>> a = [1]*50
    >>> a[20:] = zip(*zip(a[20:],itertools.repeat(0)))[1]
    
    0 讨论(0)
提交回复
热议问题