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

前端 未结 5 1145
南旧
南旧 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

    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
    

提交回复
热议问题