#39;Return#39; keyword returns only one element from a loop?(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.
这篇关于'Return' 关键字只返回循环中的一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:'Return' 关键字只返回循环中的一个元素?
基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01