-1

I have list of lists looks like

a=[[1,2],[2,1],[2,3]]

I would like to check if the fırst elements of sublist are same, if they are same I would like to put them a new list.

I tried

for x in a:
    for y in x:
        if y in x:

I could not find what to write after that. My output is that new lists like

a1=[[2,3,1],[1,2]] 

Thank you

Barmar
  • 741,623
  • 53
  • 500
  • 612
Susu
  • 53
  • 6
  • Why are you looping through `x`? You only care about the first elements of the sublists, not all the elements. – Barmar Oct 08 '20 at 01:47
  • What output do you expect? Can you work through how to get it by hand? – Mad Physicist Oct 08 '20 at 01:47
  • Use a list comprehension to get the first element of each sublist. Then see https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical for how to test if all of them are the same. – Barmar Oct 08 '20 at 01:48
  • 1
    Can you explain how that output relates to the input? I don't see the pattern. – Barmar Oct 08 '20 at 01:50
  • I added the expected output. Thanks! – Susu Oct 08 '20 at 01:50
  • Ah, I see it. `[2, 3, 1]` comes from `[2, 1] and `[2, 3]` because they both begin with `2`. – Barmar Oct 08 '20 at 01:51
  • `if y in x:` will always be true, since `y` is looping through the elements of `x`. You're comparing elements of the same sublist, not different sublists. – Barmar Oct 08 '20 at 01:52

2 Answers2

1

I'll go for dictionary.

a = [[1,2],[2,1],[2,3]]

d = {}
for x in a:
    head = x[0]
    if head in d.keys():
        d[head].extend(x[1:])
    else:
        d[head] = x[1:]

result = [[key] + d[key] for key in d.keys()]
Joonyoung Park
  • 474
  • 3
  • 6
0

Try this:

a=[[2,2],[2,1],[2,3]]
myList=[x[0] for x in a]
print(all(y==myList[0] for y in myList))

If same then True else False

Wasif
  • 14,755
  • 3
  • 14
  • 34