문제

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. 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]]

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:

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. You need to use instead

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

to have 28 unique lists.

Also, a more pythonic way of iterating over idx_n is

for i, idx in enumerate(idx_n):
    print i, idx
    cluster_entries[ int(idx) ].append( list_from_files[i] )
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top