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
168 views
in Technique[技术] by (71.8m points)

Don't understand this python For loop

I'm still a python newb, but I'm working through the Pyneurgen neural network tutorial, and I don't fully understand how the for loop used to create the input data works in this instance:

for position, target in population_gen(population):
    pos = float(position)
    all_inputs.append([random.random(), pos * factor])
    all_targets.append([target])`

What is the loop iterating through exactly? I've not come across the use of the comma and a function in the loop before.

Thanks in advance for any help :)

question from:https://stackoverflow.com/questions/65843330/question-about-python-for-loops-iteration

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

1 Reply

0 votes
by (71.8m points)

The function population_gen is returning a list of tuples, which are unpacked automatically into variable names using this syntax.

So basically, you're getting something like the following as return value from the function:

[("pos1", "target1"), ("pos2", "target2"), ]

Given this example, in the the for loop's first iteration, the variables "position" and "target" will have the values:

position = "pos1"
target = "target1"

In second iteration:

position = "pos2"
target = "target2"

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

...