'Return' 关键字只从循环中返回一个元素? [英] 'Return' keyword returns only one element from a loop?

查看:45
本文介绍了'Return' 关键字只从循环中返回一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 

这只会打印第一个元素.但是,当我用 print 替换 return 字为 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).

请参阅:产量"是什么?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.

这篇关于'Return' 关键字只从循环中返回一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆