Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表增长后的奇怪行为_Python - Fatal编程技术网

Python 列表增长后的奇怪行为

Python 列表增长后的奇怪行为,python,Python,下面的代码(对我来说)产生了非常令人惊讶的输出: cols = [ int(x) for x in sys.argv[2:] ] data = [[]] * len(cols) with open( sys.argv[1] ) as f: for l in f: c = l.split() if len(c) <= cols[-1]: continue for i in range(0,len(cols)):

下面的代码(对我来说)产生了非常令人惊讶的输出:

cols = [ int(x) for x in sys.argv[2:] ]

data = [[]] * len(cols)

with open( sys.argv[1] ) as f:
    for l in f:
        c = l.split()
        if len(c) <= cols[-1]: continue
        for i in range(0,len(cols)):
            print( i, cols[i], c[cols[i]] )
            data[i].append( float(c[cols[i]]) )
        print()

for i in range( 0, len(cols)):
    print( data[i] )
其中“file.txt”包含:

1       0       0       -21612.9       
2       0.0914607       0.0914607       -21611.6 
...       
第一次打印的输出如下所示:

0 2 0
1 3 -21612.9

0 2 0.0914607
1 3 -21611.6

...
[0.0, -21612.9, 0.0914607, -21611.6, ...
但是,第二个循环返回两个相同的列表,如下所示:

0 2 0
1 3 -21612.9

0 2 0.0914607
1 3 -21611.6

...
[0.0, -21612.9, 0.0914607, -21611.6, ...
我希望有两份清单:

[0.0, 0.0914607, ...
[-21612.9, -21611.6, ...


我知道这可以使用defaultdict来完成,但我想了解为什么该代码不起作用。我怀疑这是将“数据”声明为固定大小的空列表列表?

data=[[]]*len(cols)
更改为
data=[[]]以表示范围内的I(len(cols))]

保持一切不变。

从链接的问题中得到了关于我的定义为何表现异常的答案:它创建了对同一对象的引用。