假设您有一个列表['dogs, cats']
。如何将任意数量的['dogs', 'cats']
转换为['x, y, z']
最佳答案
只需拆分', '
上的第一个元素:
>>> ['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']