【发布时间】:2019-11-14 18:10:50
【问题描述】:
我尝试对列表A 中的每个元素进行更改,并有两种方法:use_list_comprehension(A, length) 和use_plain_loop(A, length)。两者对元素执行相同的操作,但产生不同的结果。
我的问题是:python 列表理解是否首先复制A,然后使用该副本作为源来获取元素并对其执行操作?
def arrange(A):
length = len(A)
A = use_list_comprehension(A, length) # we get [19, 20, 12, 1, 8]
# A = use_plain_loop(A, length) # we get [19, 95, 12, 476, 2383]
return A
def use_list_comprehension(A, length):
return [ A[i]+A[A[i]]*length for i in range(length) ]
def use_plain_loop(A, length):
for i in range(length):
A[i] += A[A[i]]*length
return A
print(arrange([4,0,2,1,3]))
【问题讨论】:
-
答案不同,因为列表实际上是针对
use_plain_loop修改的,因此在计算下一个值时,它使用更新后的值。
标签: python list loops list-comprehension