Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 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 Answer

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...