Py学习  »  Python

在列表python中拆分单个字符串

Starbucks • 6 年前 • 1640 次点击  

如何在列表中拆分单个字符串?

data = ('Esperanza Ice Cream', 'Gregory Johnson', 'Brandies bar and grill')

返回:

print(data)
('Esperanza', 'Ice', 'Cream', 'Gregory', 'Johnson', 'Brandies', 'bar', 'and', 'grill')
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39352
 
1640 次点击  
文章 [ 3 ]  |  最新文章 6 年前
Stephen Rauch
Reply   •   1 楼
Stephen Rauch    6 年前

你可以用 itertools.chain 对于这种情况:

代码:

it.chain.from_iterable(i.split() for i in data)

测试代码:

import itertools as it

data = ('Esperanza Ice Cream', 'Gregory Johnson', 'Brandies bar and grill')
print(list(it.chain.from_iterable(i.split() for i in data)))

结果:

['Esperanza', 'Ice', 'Cream', 'Gregory', 'Johnson', 'Brandies', 'bar', 'and', 'grill']
ComplicatedPhenomenon
Reply   •   2 楼
ComplicatedPhenomenon    6 年前
data = ('Esperanza Ice Cream', 'Gregory Johnson', 'Brandies bar and grill')
data = [i.split(' ') for i in data]
data=sum(data, [])
print(tuple(data))
#('Esperanza', 'Ice', 'Cream', 'Gregory', 'Johnson', 'Brandies', 'bar', 'and', 'grill')
Tim Biegeleisen
Reply   •   3 楼
Tim Biegeleisen    6 年前

一种方法,使用 join split :

items = ' '.join(data)
terms = items.split(' ')
print(terms)

['Esperanza', 'Ice', 'Cream', 'Gregory', 'Johnson', 'Brandies', 'bar', 'and', 'grill']

这里的想法是生成一个包含所有空格分隔项的字符串。那么,我们只需要一次调用非regex版本的 分裂 以获得输出。