[英]Iterate over a list to apply a method to each member
I have a list of strings that I want to apply a method ( .split
). 我有一个要应用方法的字符串列表(
.split
)。 I know this can be done by a for
loop but knowing the mentality of python I assume there is a better way, like the map
function 我知道这可以通过
for
循环来完成,但是了解python的思路后,我认为有更好的方法了,例如map
函数
Below is the thing I want written using for
loop 下面是我想用
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']]
You can use a simple list comprehension , like this 您可以像这样使用简单的列表理解
>>> config = ['a b','c d']
>>> [item.split() for item in config]
[['a', 'b'], ['c', 'd']]
If you want to use map
, you can pass str.split
function to it. 如果要使用
map
,可以将str.split
函数传递给它。 But, Python 3.x's map
returns an iterable map object. 但是,Python 3.x的
map
返回一个可迭代的地图对象。
>>> map(str.split, config)
<map object at 0x7f9843a64a90>
So, you need to explicitly convert that to a list, with the list
function, like this 因此,您需要使用
list
函数将其显式转换为list
,如下所示
>>> list(map(str.split, config))
[['a', 'b'], ['c', 'd']]
As an alternative to anwser by @thefourtheye you can use map
: 作为@thefourtheye的anwser的替代方案,您可以使用
map
:
config = ['a b','c d']
new_config = list(map(lambda x: x.split(), config))
print(new_config)
# [['a', 'b'], ['c', 'd']]
config = ['a b','c d']
Create an empty list 创建一个空列表
configSplit = list()
Iterate over each item, split, add to new list. 遍历每个项目,拆分,添加到新列表。
for item in config:
configSplit.append(item.split())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.