使用嵌套列表(子列表)列出理解

时间:2014-03-06 16:09:10

标签: python python-2.7 list-comprehension

以下列表理解按我想要的方式工作。我的问题是,有没有办法编写代码而不必包含所有特定的元素索引?目标是根据包含的输出将子列表的成员与其各自的外部成员合并。

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']
]
'''

1 个答案:

答案 0 :(得分:3)

使用列表连接:

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

演示:

>>> 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']]