Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

python - 'Return' keyword returns only one element from a loop?

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]

When I call this function as:

a = pass_username()
print a 

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?

Content of test.csv:

"[email protected]","rockon"
"[email protected]","hey"
"[email protected]","ok"
"[email protected]","password"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

See: What does the "yield" keyword do in Python?

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())

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...