python assign values to list elements in loop

后端 未结 4 2136
醉酒成梦
醉酒成梦 2020-11-27 06:27

Is this a valid python behavior? I would think that the end result should be [0,0,0] and the id() function should return identical values each iteration. How to make it pyth

4条回答
  •  攒了一身酷
    2020-11-27 07:03

    Yes, the output you got is the ordinary Python behavior. Assigning a new value to foo will change foo's id, and not change the values stored in bar.

    If you just want a list of zeroes, you can do:

    bar = [0] * len(bar)
    

    If you want to do some more complicated logic, where the new assignment depends on the old value, you can use a list comprehension:

    bar = [x * 2 for x in bar]
    

    Or you can use map:

    def double(x):
        return x * 2
    
    bar = map(double, bar)
    

提交回复
热议问题