0

I have a list of tuples of the form:

 list = [('A',2),('A',1),('B',3),('A',4),('B',5),('A',1)]

And I want two lists, one with all the tuples with first element 'A' and the other with tuples with first element 'B'.

 listA = [('A',2),('A',1),('A',4),('A',1)]
 listB = [('B',3),('B',5)]

Any ideas? Thank you! EDIT : Note that the list above is just as an example, my actual list is much longer and has 100+ different first elements.

MrKaplan
  • 61
  • 1
  • 5

3 Answers3

1

List comprehensions will do the trick:

listA = [x for x in list if x[0] == 'A']
listB = [x for x in list if x[0] == 'B']

Also, naming a variable list is generally a bad idea, as it overwrites the built-in list.

Marcus
  • 3,216
  • 2
  • 22
  • 22
  • That was just for my example, my actual list is much too long for list comprehensions I think, as I have 100+ different first elements – MrKaplan Jan 24 '19 at 16:54
0

Simplest and readable way is to use list comprehension:

listA = [t for t in list if t[0]=='A']
olinox14
  • 6,177
  • 2
  • 22
  • 39
0

You can try below Solution, hope this will solve your problem

ls= [('A',2),('A',1),('B',3),('A',4),('B',5),('A',1)]
key = [i[0] for i in ls]
temp = []
for i in ls:
    temp2 = []
    for j in key:
        if i[0] == j:
            temp2.append(i)
    temp.append(temp2)

output of above code is:

[[('A', 2)], [('A', 1)], [('B', 3)], [('A', 4)], [('B', 5)], [('A', 1)]]

list will convert your 1 list into list of list based on key of tuple.

Aman Jaiswal
  • 1,084
  • 2
  • 18
  • 36