我想知道,如何将空间字符的元素列表分解到另一个列表?
例如,该列表包含以下元素:
['John', 'House', '23 4500', 'grass', '542 3256']
至
['John', 'House', '23', '4500', 'grass', '542', '3256']
我想知道,如何将空间字符的元素列表分解到另一个列表?
例如,该列表包含以下元素:
['John', 'House', '23 4500', 'grass', '542 3256']
至
['John', 'House', '23', '4500', 'grass', '542', '3256']
>>> 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']
另一种方法:
>>> l = ['John', 'House', '23 4500', 'grass', '542 3256'];
>>> m = ' '.join(l).split()
['John', 'House', '23', '4500', 'grass', '542', '3256']