'Return' 关键字只返回循环中的一个元素?

2022-01-19 00:00:00 python return

问题描述

我有一个简单的函数来读取 csv 文件并从中提取第一个列:

I have a simple function to read the csv file and extracts the first coloum from it:

import csv 

def pass_username():
    with open('test.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
        for row in spamreader:
            return row[0]

当我把这个函数称为:

a = pass_username()
print a 

这只会打印第一个元素.但是,当我将 return 单词替换为 print 作为 print row[0] 并将函数调用为 pass_username() 它打印所有元素.我想将该函数分配给一个变量,因此我想使用 return.如何解决?

This only prints the first element. However, when I replace return word with print as print row[0] and call the function as pass_username() it prints all the elements. I want to assign that function to a variable thus I want to use return. How to fix it?

test.csv 的内容:

Content of test.csv:

"test@gmail.com","rockon"
"hello@gmail.com","hey"
"hithere@gmail.com","ok"
"hellosir@gmail.com","password"


解决方案

正如其他回答的人所说,您可以将结果累积到一个列表中并返回.但是,另一种方法是将 return 替换为 yield ,这会导致您的函数返回一个可迭代类型对象,该对象会在您决定稍后对其进行迭代时生成您产生的项目(可能带有 for 循环).

As the other people who answered said, you can accumulate the results into a list and return that. Another way though, would be to replace return with yield which causes your function to return an iterable type object that produces the items you yield when you decide to iterate over it later (possibly with a for loop).

请参阅:yield"是什么意思?Python中的关键字do?

以下是您将如何在代码中使用它:

Here is how you would use it with your code:

import csv 

def pass_username():
    with open('test.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
        for row in spamreader:
            yield row[0]

username_generator = pass_username()

# iterate through the usernames with a for loop
for name in username_generator:
    print name
# call the list constructor which causes it to produce all of the names
print list(pass_username())

请记住,用户名是根据需要生成的,因此您可以,例如,执行 username_generator.next() 这将生成下一个用户名,而无需必须全部生产.

Keep in mind that the usernames are produced as they are needed, so you can, for example, do username_generator.next() which will produce the next username without having to produce all of them.

相关文章