拆分列表中的列表

时间:2014-04-05 14:27:52

标签: python list split element

输入:

[['Tryndamere', 'Barbarian', 'Fighter'],['Caitlyn', 'Sheriff', 'Marksmen'],...['Veigar', 'Midget', 'Mage']]

预期产出:

['Barbarian']['Caitlyn']['Fighter']['Mage']['Marksmen']['Midget']['Sheriff']['Tryndamere']['Veigar']...

问题: 如何将列表中的列表分开,直到它们成为单个元素?谢谢你们

2 个答案:

答案 0 :(得分:2)

让我们说数据看起来像这样

>>> lists = [
...     ['Tryndamere', 'Barbarian', 'Fighter'],
...     ['Caitlyn', 'Sheriff', 'Marksmen'],
...     ['Veigar', 'Midget', 'Mage']
... ]

然后,你可以像这样使用列表理解

>>> from pprint import pprint
>>> pprint([[item] for c_list in lists for item in c_list])
[['Tryndamere'],
 ['Barbarian'],
 ['Fighter'],
 ['Caitlyn'],
 ['Sheriff'],
 ['Marksmen'],
 ['Veigar'],
 ['Midget'],
 ['Mage']]

或使用itertools.chain

>>> from itertools import chain
>>> pprint([[item] for item in chain.from_iterable(lists)])
[['Tryndamere'],
 ['Barbarian'],
 ['Fighter'],
 ['Caitlyn'],
 ['Sheriff'],
 ['Marksmen'],
 ['Veigar'],
 ['Midget'],
 ['Mage']]

但是如果您考虑将这些列表展平为一个列表,请检查this。您可以轻松扩展chain版本来执行此操作,例如

>>> pprint(list(chain.from_iterable(lists)))
['Tryndamere',
 'Barbarian',
 'Fighter',
 'Caitlyn',
 'Sheriff',
 'Marksmen',
 'Veigar',
 'Midget',
 'Mage']

或列表推导版本,

>>> pprint([item for c_list in lists for item in c_list])
['Tryndamere',
 'Barbarian',
 'Fighter',
 'Caitlyn',
 'Sheriff',
 'Marksmen',
 'Veigar',
 'Midget',
 'Mage']

答案 1 :(得分:0)

只需使用遍历子列表的列表推导。然后,您可以将该字符串转换为长度为1的列表,只需将其包装在方括号中即可。

>>> lst = [['Tryndamere', 'Barbarian', 'Fighter'], 
           ['Caitlyn', 'Sheriff', 'Marksmen'], 
           ['Veigar', 'Midget', 'Mage']]
>>> [[item] for sub in lst for item in sub]
[['Tryndamere'], ['Barbarian'], ['Fighter'], ['Caitlyn'], ['Sheriff'], ['Marksmen'], ['Veigar'], ['Midget'], ['Mage']]