将列表分解为空格字符的另一个列表

时间:2013-04-12 21:01:24

标签: python

我想知道,我怎样才能将其中的空间字符列表中的列表分解为另一个列表?

对于exaple,列表包含以下元素:

['John', 'House', '23 4500', 'grass', '542 3256']

['John', 'House', '23', '4500', 'grass', '542', '3256']

2 个答案:

答案 0 :(得分:5)

>>> L = ['John', 'House', '23 4500', 'grass', '542 3256']
>>> [y for x in L for y in x.split()]
['John', 'House', '23', '4500', 'grass', '542', '3256']

可替换地:

>>> from itertools import chain
>>> list(chain.from_iterable(map(str.split, L)))
['John', 'House', '23', '4500', 'grass', '542', '3256']

答案 1 :(得分:3)

另一种方法:

>>> l = ['John', 'House', '23 4500', 'grass', '542 3256'];
>>> m = ' '.join(l).split()
['John', 'House', '23', '4500', 'grass', '542', '3256']