简体   繁体   English

遍历列表以将方法应用于每个成员

[英]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.

相关问题 遍历列表,应用 function 并将每个 output 设置为 pandas Z6A80064D5DF479C5553 的行 - iterate over a list, apply a function and set each output to rows of a pandas dataframe 遍历数据帧字典并将 function 应用于每个 dataframe - iterate over a dictionary of dataframes and apply function to each dataframe 如何迭代后缀列表以添加到列表中每个变量的末尾? - How to iterate over a list of suffixes to add to the end of each variable in a list? 迭代第一个列表[]中的每个值到另一个列表[]上以形成字典{} - Iterate each value in the first list [] over another list [] to form dictionary {} Python:如何遍历列表列表,同时遍历每个嵌套列表中的每个项目 - Python: how to iterate over list of list while iterating over each item in each nested list 如何迭代重复Python中每个元素的列表 - How to iterate over a list repeating each element in Python 如何遍历字符串列表中的每个字符串并对其元素进行操作? - How to iterate over each string in a list of strings and operate on its elements? 遍历字符串并将模式移动到每个列表元素的开头 - iterate over strings and move pattern to start of each list element 遍历 URL 列表并使用 Selenium 打开每个 URL - Iterate over list of URLs and open each url with Selenium 使用 reduce 迭代函数列表并调用每个函数 - Using reduce to iterate over list of functions and call each one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM