0

I haves been looking for an answer to this but can't seem to find anything that does this elegantly or pythonic.

Basically if I have a list:

A = [["1a", "ab"], ["2b", "cd"], ["1a", "ef"]]

I want to identify every item which has the same value in their first index and if that's the case amend the list so that A becomes:

A = [["1a", ["ab", "ef"]], ["2b", "cd"]]

As ordering is important I am trying to avoid dictionaries.

  • 1
    https://stackoverflow.com/a/39537308/1400768 – nhahtdh Sep 11 '18 at 03:15
  • 1
    Possible duplicate of [Dictionaries: How to keep keys/values in same order as declared?](https://stackoverflow.com/questions/1867861/dictionaries-how-to-keep-keys-values-in-same-order-as-declared) – nhahtdh Sep 11 '18 at 03:15
  • Why not `["2b", ["cd"]]` – Mad Physicist Sep 11 '18 at 03:35
  • Per my question I am trying to avoid using a dictionary as it does not preserve the order of the list (at least in 2.6) – Laughingwithu Sep 11 '18 at 03:35
  • @Laughingwithu see mine – U13-Forward Sep 11 '18 at 03:35
  • @mad physicist there would be no issue with that as it's still simple to access. I am playing with U9-Forward's answer as it works albiet I need to delete the duplicated lists (I need to read up about zip about more obviously as i did not realise you can create a tuple the way he/she has) – Laughingwithu Sep 11 '18 at 03:44

1 Answers1

0

Try zip + list comprehension + product + for-loop + indexing (even works for below list):

from itertools import product
A = [["1a", "ab"], ["2b", "cd"], ["1a", "ef"], ['2b','gh']]
l,_=zip(*A)
l2=[idx for idx,i in enumerate(l) if l.count(i)>1]
l3=list(set([tuple(sorted((x,y))) for x,y in product(l2,repeat=2) if l[x]==l[y] and x!=y]))
for x,y in l3:
   A[x][1]=[A[x][1],A[y][1]]
   A.pop(y)
print(A)

Output:

[['1a', ['ab', 'ef']], ['2b', ['cd', 'gh']]]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114