简体   繁体   English

如何从 Python 中的生成器打印参数?

[英]how to print args from a Generator in Python?

i wanna solve a subject in my University so, i have to create a function with parametres(*args).我想在我的大学解决一个主题,所以我必须创建一个带有参数(* args)的函数。 After that i have to find the average of all of them.之后,我必须找到所有这些的平均值。 Continues with a math type.. we have to print out the square of abstraction per-element - average and i have to use a Generator.继续数学类型..我们必须打印出每个元素的抽象平方 - 平均值,我必须使用生成器。 For eg: i have the function "squares(*args). when i call it like "squares(3,4,5) we find the average, 4 for this eg and we start the abstraction.例如:我有函数“squares(*args)。当我把它称为“squares(3,4,5)”时,我们找到平均值,这个eg为4,然后我们开始抽象。 3-4 , 4,4, 5,-4 but also we need the square of it. 3-4 , 4,4, 5,-4 但我们也需要它的平方。 So (3-4)**2 and etc. I have this code but.. doesn't work, any idea?所以 (3-4)**2 等等。我有这个代码但是..不起作用,知道吗?

from statistics import mean
def squares(*args):
  avg=mean(args)
  i = 0
  while (i <= len(args)):
    yield (args[i]-avg)**2
    i=i+1
squares(2, 7, 3, 12)
for k in squares():
  print(k)

Issue here:问题在这里:

squares(2, 7, 3, 12)
for k in squares():
  print(k)

you're calling squares() a first time - which returns a generator object that you discard (you don't assign it to a variable).您第一次调用squares() - 它返回一个您丢弃的生成器对象(您没有将其分配给变量)。 Then you call it a second time and iterate over the returned generator, but since you didn't pass any argument the genrator is "empty" (it has nothing to yield) and the for loop's body doesn't execute.然后你第二次调用它并迭代返回的生成器,但是由于你没有传递任何参数,生成器是“空的”(它没有任何东西可以产生)并且 for 循环的主体不会执行。

IOW, replace this with: IOW,将其替换为:

squared = squares(2, 7, 3, 12)
for k in squared:
  print(k)

Or just simply:或者只是简单地:

for k in squares(2, 7, 3, 12):
  print(k)

NB: I didn't test you code, it might have other issues...注意:我没有测试你的代码,它可能有其他问题......

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

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