简体   繁体   English

从循环中创建值列表

[英]Making a list of values from a loop

I'm making a program as practice that would set a random number up to 400 for N, and a counter named K would be increased by one each time.我正在编写一个程序作为练习,它将为 N 设置一个最大为 400 的随机数,并且一个名为 K 的计数器每次都会增加一。 At the end, I would like it to make a list of all of the values that were assigned to N.最后,我希望它列出分配给 N 的所有值。

Does anyone know how to do this?有谁知道如何做到这一点?

import random
separateur = "============================================================"
def Compteur_bulletins():
  K = 0
  N = 36
  while N >= 36:
      N = random.randint(1,400)
      K += 1
  print("Nombre de bulletins au-dessus ou egal a 36: ", K)
  print("Valeure de 'N': ", N, "\n")
  print(separateur, "\n")
  return K, N

for x in range(10):
  Compteur_bulletins()

Try this:尝试这个:

def compteur_bulletins():
    k = 0
    values_of_n = []
    n = random.randint(1, 400)
    while n >= 36:
        values_of_n.append(n)
        n = random.randint(1, 400)
        k += 1

    return values_of_n, k

values, count = compteur_bulletins()
print('K:', count)
print(values)
print('Sum:', sum(values))

Output:输出:

K: 15
[193, 114, 203, 227, 328, 262, 133, 311, 211, 323, 86, 310, 226, 147, 223]
Sum: 3297

Or, if you want 10 different sums of the values of n as you have done in your code, you can do this:或者,如果您想要 10 个不同的n值的总和,就像您在代码中所做的那样,您可以这样做:

for _ in range(10):
    values, count = compteur_bulletins()
    print(sum(values))

Output:输出:

471
0
3243
1348
896
808
2865
867
0
2447

If the goal is to exclude the first value of N (36) and the final value of N (the one below 36), then something like this will work:如果目标是排除 N 的第一个值 (36) 和 N 的最终值(低于 36 的值),那么这样的事情将起作用:

import random
separateur = "============================================================"
def Compteur_bulletins():
  K = 0
  N = 36
  valeures_N = []
  while N >= 36:
      if K >= 1:
          valeures_N.append(N)
      N = random.randint(1,400)
      K += 1
  print("Nombre de bulletins au-dessus ou egal a 36: ", K)
  print("Valeure de 'N': ", N, "\n")
  print("Valeures anciennes de 'N': ",valeures_N, "\n") 
  print("Somme:",sum(valeures_N))
  print(separateur, "\n")
  return K, N, valeures_N

for x in range(10):
  Compteur_bulletins()

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

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