[英]How to apply a function or command to every row of a list?
I have a list of items in a string with 2 columns and dozens of rows.我有一个包含 2 列和数十行的字符串中的项目列表。 I want to filter out every item from one of the columns.
我想从其中一列中过滤掉每个项目。 I think I can do this by applying the.split command on each row but if there's any better way to do this that doesn't involve regex I'd like to know.
我想我可以通过在每一行上应用 .split 命令来做到这一点,但如果有任何更好的方法来做到这一点,我想知道不涉及正则表达式。
Edit: I'm trying to do this with a list of names like:编辑:我正在尝试使用以下名称列表来执行此操作:
"""Roy Theresa
Vincent Diana
Ralph Natalie
Eugene Brittany""" etc.
When I use:当我使用时:
head, sep, tail = nameList.partition(' ')
print(head)
It only returns the first name in the list.它只返回列表中的第一个名字。 I want to apply that code to every line of the string so I can get the first name off every line instead of just the first one in the whole list.
我想将该代码应用于字符串的每一行,这样我就可以从每一行中获取名字,而不仅仅是整个列表中的第一个。
If you have a direct list like:如果您有一个直接列表,例如:
a = ["Roy Theresa","Vincent Diana","Ralph Natalie","Eugene Brittany"]
then all you have to do is:那么你所要做的就是:
for i in a:
print(i.split(" ")[0])
to get the first world from each element of the list.从列表的每个元素中获取第一个世界。
But if you have a String like:但是如果你有一个像这样的字符串:
b = """Roy Theresa
Vincent Diana
Ralph Natalie
Eugene Brittany"""
First you must divide it into different names using splitlines() and repeat the top step once you get a list of names, like this:首先,您必须使用 splitlines() 将其分成不同的名称,并在获得名称列表后重复上面的步骤,如下所示:
new_list = b.splitlines()
for i in new_list:
print(i.split(" ")[0])
Your output will be:您的 output 将是:
Roy
Vincent
Ralph
Eugene
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.