简体   繁体   中英

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

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"

Tuple unpacking.

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

And the function is just a function.

The function either returns a sequence or serves as something called a "generator:" it spits out successive elements in a sequence for the caller to iterate through. This question concerning the yield keyword has some thorough discussion of how these work.

As for the comma, since the function (apparently) returns a two-tuple, the comma-separated list of names is a convenient way to name individual elements of the tuple without having to unpack them yourself.

It's called tuple unpacking . The population_gen (generator) function yields tuples containing exactly two elements. In python, you can assign several variables to tuples like this

a, b = (1, 2)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM