【问题标题】:Making a list of values from a loop从循环中创建值列表
【发布时间】:2018-07-25 10:39:40
【问题描述】:

我正在编写一个程序作为练习,它将为 N 设置一个最大为 400 的随机数,并且一个名为 K 的计数器每次都会增加一。最后,我希望它列出分配给 N 的所有值。

有人知道怎么做吗?

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

【问题讨论】:

  • 您能否详细说明问题所在?
  • 你的意思是每次都会增加?什么时候结束增加?
  • 基本上问题是我试图在while循环中获取分配给N的所有ranodm值的列表。 K只是一个计数器,N每大于等于36就加一
  • 你遇到了什么问题?
  • 您的目标是生成 36 到 400 之间的随机项目,如果是,为什么不使用 random.randint(36,400)

标签: python python-3.x loops numbers list-comprehension


【解决方案1】:

试试这个:

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

输出:

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

或者,如果您想要 10 个不同的 n 值总和,就像您在代码中所做的那样,您可以这样做:

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

输出:

471
0
3243
1348
896
808
2865
867
0
2447

【讨论】:

    【解决方案2】:

    如果目标是排除 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()
    

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 2019-06-19
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多