在Python中的空格处拆分列表中的每个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13808592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:40:17  来源:igfitidea点击:

Splitting each string in a list at spaces in Python

pythonlisturlsplit

提问by Arc'

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!

我有一个列表,其中包含一个 url 和 Python 中大型列表的每个项目中的一些文本。每次出现空格时,我想将每个项目拆分为多个项目(每个项目 2-3 个空格)。没有太多代码要发布,它只是目前存储在命名变量中的列表。我试过使用 split 功能,但我似乎无法正确使用。任何帮助将不胜感激!

回答by ank

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

回答by Mark Ransom

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