输入:
[['Tryndamere', 'Barbarian', 'Fighter'],['Caitlyn', 'Sheriff', 'Marksmen'],...['Veigar', 'Midget', 'Mage']]
预期产出:
['Barbarian']['Caitlyn']['Fighter']['Mage']['Marksmen']['Midget']['Sheriff']['Tryndamere']['Veigar']...
问题: 如何将列表中的列表分开,直到它们成为单个元素?谢谢你们
答案 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']]
>>> 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']]