假设您有一个列表['dogs, cats']
。如何将其转换为['dogs', 'cats']
任意数量的['x, y, z']
答案 0 :(得分:7)
只需拆分', '
上的第一个元素:
>>> ['dogs, cats'][0].split(', ')
['dogs', 'cats']
>>>
>>> ['x, y, z'][0].split(', ')
['x', 'y', 'z']
如果您的列表中可以有多个以逗号分隔的字符串,则可以使用list comprehension:
>>> 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']
答案 1 :(得分:0)
使用split(',')为您提供List
list = ['dogs,cats','x,y,z']
finalList = []
列表中的键: finalList.extend(key.split(','))
你会得到的 ['x','y','z','dog','cats']