如何通过索引连接列表中的元素?

时间:2014-10-04 08:39:34

标签: python list

我有清单:

['0.125', '0', 'A']
['0.5', '0', 'B', ' A']
['0.75', '0', 'C']
['0.5', '0.5', 'D', ' C', 'A']

我想要

['0.125', '0', 'A']
['0.5', '0', 'B']
['0.5', '0', 'A']
['0.75', '0', 'C']
['0.5', '0.5', 'D']
['0.5', '0.5', 'C']
['0.5', '0.5', 'A']

执行此操作的任何指南?

1 个答案:

答案 0 :(得分:2)

您可以使用嵌套列表解析:

[sub[:2] + [elem] for sub in yourlist for elem in sub[2:]]

演示:

>>> yourlist = [
...     ['0.125', '0', 'A'],
...     ['0.5', '0', 'B', ' A'],
...     ['0.75', '0', 'C'],
...     ['0.5', '0.5', 'D', ' C', 'A'],
... ]
>>> from pprint import pprint
>>> [sub[:2] + [elem] for sub in yourlist for elem in sub[2:]]
[['0.125', '0', 'A'], ['0.5', '0', 'B'], ['0.5', '0', ' A'], ['0.75', '0', 'C'], ['0.5', '0.5', 'D'], ['0.5', '0.5', ' C'], ['0.5', '0.5', 'A']]
>>> pprint(_)
[['0.125', '0', 'A'],
 ['0.5', '0', 'B'],
 ['0.5', '0', ' A'],
 ['0.75', '0', 'C'],
 ['0.5', '0.5', 'D'],
 ['0.5', '0.5', ' C'],
 ['0.5', '0.5', 'A']]