简体   繁体   English

列表选择性插入的Python列表

[英]Python list of list selective insertion

I have two lists both of them of the same size I have 28 sets, and I need to count how many elements per set there are, these sets may also be empty, since they are the fruit of a clustering analysis. 我有两个列表,它们的大小相同,我有28个集合,并且我需要计算每个集合中有多少个元素,这些集合也可能是空的,因为它们是聚类分析的结果。 I was thinking to have a list of lists called cluster_entries such as cluster_entries = [[0]*28], and then appending the corresponding value found ad idx_n[i] to the corresponding cluster_entries[idx_n[i]] 我在考虑有一个名为cluster_entries的列表的列表,例如cluster_entries = [[0] * 28],然后将在idx_n [i]中找到的对应值附加到相应的cluster_entries [idx_n [i]]

so for instance if I have idx_n[20] = 10 I would like to add to the list 20 of cluster_entries the value 20. Thus I wrote the following code: 因此,例如,如果我的idx_n [20] = 10,我想将20的值添加到cluster_entries的列表20中。因此,我编写了以下代码:

for i in range(len(idx_n)):
    print i, idx_n[i]
    cluster_entries[int(idx_n[i])].append(list_from_files[i])

Unfortunately this code appends always to the first element... and I do not understand why 不幸的是,这段代码总是附加到第一个元素上。。。我不明白为什么

Your list 您的清单

cluster_entries = [[0]*28]

is a list of 28 identical references to the same list. 是对相同列表的28个相同引用的列表。 You need to use instead 您需要使用

cluster_entries = [ [0] for i in range(28) ]

to have 28 unique lists. 拥有28个唯一列表。

Also, a more pythonic way of iterating over idx_n is 另外,在idx_n上进行迭代的一种更idx_n

for i, idx in enumerate(idx_n):
    print i, idx
    cluster_entries[ int(idx) ].append( list_from_files[i] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM