1

Say you have a list ['dogs, cats']. How can one turn that into ['dogs', 'cats'] for arbitrary number of ['x, y, z']

4

2 回答 2

7

只需将第一个元素拆分为', '

>>> ['dogs, cats'][0].split(', ')
['dogs', 'cats']
>>>
>>> ['x, y, z'][0].split(', ')
['x', 'y', 'z'] 

如果您的列表中可以有多个逗号分隔的字符串,那么您可以使用列表推导:

>>> li = ['x, y, z', 'dogs, cats']
>>> 
>>> li2 = [elem.split(', ') for elem in li]
>>> [v for val in li2 for v in val]
['x', 'y', 'z', 'dogs', 'cats']

或使用sum()过度列表理解:

>>> li = ['x, y, z', 'dogs, cats']
>>>
>>> sum([elem.split(', ') for elem in li], [])
['x', 'y', 'z', 'dogs', 'cats']

最后是 itertools

>>> list(itertools.chain.from_iterable(elem.split(', ') for elem in li))
['x', 'y', 'z', 'dogs', 'cats']
于 2013-08-09T19:46:12.493 回答
0

使用 split(', ') 它为您提供列表

list = ['狗,猫','x,y,z']

最终列表 = []

对于列表中的键:finalList.extend(key.split(', '))

你会得到 ['x', 'y', 'z', 'dogs', 'cats']

于 2013-08-10T12:53:06.167 回答