Don't understand this python for loop

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

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

What is a cycle repeating exactly? I have not encountered using a comma and function in a loop before.

Thanks in advance for any help :)

+8
python
source share
4 answers

The population_gen function returns a list of tuples that are automatically unpacked into variable names using this syntax.

So, as the return value from the function, you get the following value:

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

In this example, in the first iteration of the for loop, the variables "position" and "target" will have the following values:

 position = "pos1" target = "target1" 

In the second iteration:

 position = "pos2" target = "target2" 
+11
source share

Unpacking package.

 for a, b in [(1, 2), (3, 4)]: print a print b print 'next!' 

And a function is just a function.

+3
source share

A function either returns a sequence or serves as something called a “generator”: it splashes out successive elements in a sequence in which the caller can iterate. This question regarding the yield keyword contains some detailed discussion of how they work.

As for the comma, since the function (apparently) returns a binary set, a list of names separated by commas is a convenient way to name the individual elements of a tuple without unpacking them yourself.

+3
source share

He caused the unpacking of the tuples . The population_gen function (generator) gives tuples containing exactly two elements. In python, you can assign multiple variables to tuples like this

 a, b = (1, 2) 

So, in this for loop, you directly put two tuple values ​​from the current iteration element into your two position and target variables.

+2
source share

All Articles