简体   繁体   English

不明白这个python For循环

[英]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: 我仍然是一个python newb,但我正在通过Pyneurgen神经网络教程 ,我不完全理解用于创建输入数据的for循环如何在这个实例中工作:

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. 函数population_gen返回一个元组列表,这些元组使用这种语法自动解压缩为变量名。

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: 在这个例子中,在for循环的第一次迭代中,变量“position”和“target”将具有以下值:

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. 该函数要么返回一个序列,要么作为一个称为“generator:”的东西,它会在序列中吐出连续的元素,以便调用者遍历。 This question concerning the yield keyword has some thorough discussion of how these work. 关于yield关键字的这个问题对这些如何工作有一些深入的讨论。

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. population_gen (generator)函数产生的元组恰好包含两个元素。 In python, you can assign several variables to tuples like this 在python中,您可以将多个变量分配给这样的元组

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 . 所以在这个for循环中,你直接将当前迭代项中的两个元组值放入你的两个变量positiontarget

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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