我有清单:
['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']
执行此操作的任何指南?
答案 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']]