Michael Swartz
Michael Swartz

Reputation: 858

List comprehension with nested lists (sublists)

The below list comprehension works the way I want it to. My question is, is there a way to write the code without having to include all the specific element indices? The goal is to consolidate members of the sublists with their respective outer member, as per the included output.

myList = [['pKey_a', ['va1', 'va2', 'va3', 'va4']], ['pKey_b', ['vb1', 'vb2', 'vb3', 'vb4']], ['pKey_c', ['vc1', 'vc2', 'vc3', 'vc4']], ['pKey_d', ['vd1', 'vd2', 'vd3', 'vd4']], ['pKey_e', ['ve1', 've2', 've3', 've4']]]

myListComp = [[d[0], d[1][0], d[1][1], d[1][2], d[1][3]] for d in myList]

print myListComp
'''
[
['pKey_a', 'va1', 'va2', 'va3', 'va4'],
['pKey_b', 'vb1', 'vb2', 'vb3', 'vb4'],
['pKey_c', 'vc1', 'vc2', 'vc3', 'vc4'],
['pKey_d', 'vd1', 'vd2', 'vd3', 'vd4'],
['pKey_e', 've1', 've2', 've3', 've4']
]
'''

Upvotes: 0

Views: 69

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121634

Use list concatenation:

myListComp = [d[:1] + d[1] for d in myList]

Demo:

>>> myList = [['pKey_a', ['va1', 'va2', 'va3', 'va4']], ['pKey_b', ['vb1', 'vb2', 'vb3', 'vb4']], ['pKey_c', ['vc1', 'vc2', 'vc3', 'vc4']], ['pKey_d', ['vd1', 'vd2', 'vd3', 'vd4']], ['pKey_e', ['ve1', 've2', 've3', 've4']]]
>>> [d[:1] + d[1] for d in myList]
[['pKey_a', 'va1', 'va2', 'va3', 'va4'], ['pKey_b', 'vb1', 'vb2', 'vb3', 'vb4'], ['pKey_c', 'vc1', 'vc2', 'vc3', 'vc4'], ['pKey_d', 'vd1', 'vd2', 'vd3', 'vd4'], ['pKey_e', 've1', 've2', 've3', 've4']]

Upvotes: 3

Related Questions