Splitting each string in a list at spaces in Pytho

2019-02-21 07:18发布

问题:

This question already has an answer here:

  • How can I replace a text delimited string list item with multiple list items in a python list? 12 answers

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!

回答1:

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']


回答2:

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']