迭代列表以将方法应用于每个成员

Oga*_*anM 0 python string list python-3.x

我有一个字符串列表,我想应用一个方法(.split).我知道这可以通过一个for循环完成,但是知道python的心态我认为有更好的方法,比如map函数

下面是我想用for循环编写的东西

config = ['a b', 'c d']

configSplit = [None] * len(config)
for x in range(len(config)):
    configSplit[x] = config[x].split()

configSplit
> [['a', 'b'], ['c', 'd']]
Run Code Online (Sandbox Code Playgroud)

the*_*eye 5

你可以使用一个简单的列表理解,就像这样

>>> config = ['a b','c d']
>>> [item.split() for item in config]
[['a', 'b'], ['c', 'd']]
Run Code Online (Sandbox Code Playgroud)

如果要使用map,可以将str.split功能传递给它.但是,Python 3.x会map返回一个可迭代的地图对象.

>>> map(str.split, config)
<map object at 0x7f9843a64a90>
Run Code Online (Sandbox Code Playgroud)

因此,您需要使用该list函数将其显式转换为列表,如下所示

>>> list(map(str.split, config))
[['a', 'b'], ['c', 'd']]
Run Code Online (Sandbox Code Playgroud)