Splitting each string in a list at spaces in Pytho

2019-02-21 06:24发布

I've got a list that contains a url and some text in each item of a large list in Python. I'd like to split each item in several items every time a space appears (2-3 spaces per item). There isn't much code to post, its just a list stored in a named variable at the moment. I've tried using the split function but I just can't seem to get it right. Any help would be greatly appreciated!

2条回答
成全新的幸福
2楼-- · 2019-02-21 06:59

You can try something like that:

>>> items = ['foo bar', 'baz', 'bak foo bar']
>>> new_items = []
>>> for item in items:
...     new_items.extend(item.split())
...
>>> new_items
['foo', 'bar', 'baz', 'bak', 'foo', 'bar']
查看更多
Viruses.
3楼-- · 2019-02-21 07:00

It's hard to know what you're asking for but I'll give it a shot.

>>> a = ['this is', 'a', 'list with  spaces']
>>> [words for segments in a for words in segments.split()]
['this', 'is', 'a', 'list', 'with', 'spaces']
查看更多
登录 后发表回答