0

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

asked Oct 17, 2021 at 10:30
2
  • Is there any significance of SourceSelection[1] or is it purely there for indexing purposes? Commented Oct 17, 2021 at 10:39
  • It is purpely for indexing purposes Commented Oct 17, 2021 at 10:49

1 Answer 1

1

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.

answered Oct 17, 2021 at 10:49
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.