迭代多维列表,结果没有意义

时间:2017-11-09 03:57:59

标签: python python-2.7 for-loop multidimensional-array

有人可以向我解释为什么这段代码(python 2.7):

$ cat f1
111,222,560,0.7
111,333,560,0.2
111,444,560,0.1

$ cat f2
2017,111,560,0.0537
2018,111,560,0.0296
2019,111,560,0.0624

$ awk 'BEGIN{FS=OFS=","}{k=$1 FS $3}FNR==NR{a[k]=(k in a ? a[k] RS:"") $2 OFS $NF; next}{k=$2 FS $3}k in a{split(a[k],t,RS); for(i=1; i in t; i++)print $0,t[i] | "sort -t, -nk5" }' f1 f2
2017,111,560,0.0537,222,0.7
2018,111,560,0.0296,222,0.7
2019,111,560,0.0624,222,0.7
2017,111,560,0.0537,333,0.2
2018,111,560,0.0296,333,0.2
2019,111,560,0.0624,333,0.2
2017,111,560,0.0537,444,0.1
2018,111,560,0.0296,444,0.1
2019,111,560,0.0624,444,0.1

结果如下:

k=0
img = [[0]*4]*5
for i in xrange(len(img)):
    for j in xrange(len(img[0])):
        k+=1
        img[i][j] = k
print(img)

而不是:

[[17, 18, 19, 20], 
 [17, 18, 19, 20],
 [17, 18, 19, 20],
 [17, 18, 19, 20],
 [17, 18, 19, 20]]

我不确定我错过了什么......?

1 个答案:

答案 0 :(得分:1)

这一行是img = [[0]*4]*5

基本上,您正在创建对数组的引用,而不是创建新数组(对于第二维)。这就解释了为什么最后一行是整个重复的行,因为它是最后一行要迭代的行。