追加项目在Python列表的列表 [英] Appending items to a list of lists in python
问题描述
我惹毛了与索引功能,并不能说明什么,我做错了。
I'm getting mad with list indexes, and can't explain what I'm doing wrong.
我有这块code,其中我想创建一个列表的列表,每一个都包含相同的电路参数的值,我是从一读(电压,电流等。) CSV
文件看起来像这样:
I have this piece of code in which I want to create a list of lists, each one containing values of the same circuit parameter (voltage, current etc..) that I'm reading from a csv
file that looks like this:
Sample, V1, I1, V2, I2
0, 3, 0.01, 3, 0.02
1, 3, 0.01, 3, 0.03
等。我想是创建例如包含V1和I1名单(我想交互选择)的形式[V1],[I1],所以:
And so on. What I want is to create a list that for example contains V1 and I1 (but I want to chose interactively) in the form [[V1], [I1]], so:
[[3,3], [0.01, 0.01]]
在code,我使用的是:
The code that I'm using is this:
plot_data = [[]]*len(positions)
for row in reader:
for place in range(len(positions)):
value = float(row[positions[place]])
plot_data[place].append(value)
plot_data code>是包含所有值的列表,而
位置
与列的索引列表我想从的.csv
复制文件。现在的问题是,如果我尝试在外壳的命令,似乎工作,但如果我运行脚本,而不是附加的每个值到适当的子列表,它附加到所有列表中的所有值,所以我得到2(或更多)相同的列表。
plot_data
is the list that contains all the values, while positions
is a list with the indexes of the columns that I want to copy from the .csv
file. The problem is that if I try the commands in the shell, seems to work, but if I run the script instead of appending each value to the proper sub-list, it appends all values to all lists, so I obtain 2 (or more) identical lists.
推荐答案
Python列表是可变的,对象和位置:
Python lists are mutable objects and here:
plot_data = [[]] * len(positions)
你重复相同的列表 LEN(职位)
倍。
>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>>
在您的列表中的每个列表是相同的对象的引用。您修改一个,你看到的修改在所有这些的。
Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.
如果你想要不同的列表,你可以这样说:
If you want different lists, you can do this way:
plot_data = [[] for _ in positions]
例如:
>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]
这篇关于追加项目在Python列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!