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

前端 未结 5 1155
南旧
南旧 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: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]
    

提交回复
热议问题