A9M
A9M

Reputation: 55

Python, appending from a list to a dependant on the value in the list

Morning all, I have a little query which I am struggling to find a way to program efficiently, what I would like to do is have a two dimensional list [[1, 1, 2, 1], [1, 2, 3, 4]] and I would like to check through the [0] index of this list and if the same numbers appears more than once I would like to appended it to separate list. So in my example list above I would like to output Source1List = [1,2,4] Source2List = [3] The index [0] of the two dimensional list is always changing whilst index [1] will never change. I have began with something like this but cant get it working currently

SourceSelection = [[1 ,2 , 1, 1], [1, 2, 3, 4]]


DisplayGroup1= []
DisplayGroup2= []
DisplayGroup3= []
DisplayGroup4= []
Groups= [DisplayGroup1,DisplayGroup2,DisplayGroup3, DisplayGroup4 ]

for source in SourceSelection[0]:
    #is there a way to grab what position source sits in the first list without knowing what number is it?
    Groups[source -1].append(SourceSelection[1][Pull the position that source sits in first list])

I sadly wont know what numbers are in the list of index [0] so i dont think i can use the .index function without an error?

Thank you in advance

Upvotes: 0

Views: 102

Answers (1)

Andrew Wei
Andrew Wei

Reputation: 902

Based on your description of the problem, you can do something like this, where you use a dictionary instead of a list of lists.

from collections import defaultdict
SourceSelection = [[1, 2, 1, 1], [1, 2, 3, 4]]

# Use dictionary because we don't know what's in index 0 of SourceSelection
Groups = defaultdict(list)

for i in range(len(SourceSelection[0])):
    source = SourceSelection[0][i]
    Groups[source].append(SourceSelection[1][i])

# Pass to remove entries with only 1
to_remove = set()
for g in Groups:
    if len(Groups[g]) == 1:
        to_remove.add(g)

for g in to_remove:
    del Groups[g]

# Print results
for g in sorted(Groups):
    print(g, Groups[g])

If you need to use a list of lists, you can just generate the initial list by finding the number of distinct elements and creating a map that stores which number maps to which index.

Upvotes: 1

Related Questions