【问题标题】:how to iterate over random range in python and count results如何在python中迭代随机范围并计算结果
【发布时间】:2020-10-01 15:47:34
【问题描述】:

我是编程新手,我正在尝试创建一个随机数迭代器,它将接受一个 numpy 随机范围并计算 1-10 中每个单独数字出现的次数。

示例: 随机范围从 1 到 5,它将计算#s 出现的次数。 count1 出现一次,count2 出现 3 次,count 9 出现一次。

代码:

import numpy as np

x1 = np.random.random(10)


count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0 
count10 = 0

for x in range(1,x1): 
  if x == 1:
    count1 += count1
  elif x == 2:
    count2 += count2
  elif x == 3:
    count3 += count3
  elif x == 4:
    count4 += count4
  elif x == 5:
    count5 += count5
  elif x == 6:
    count6 += count6
  elif x == 7:
    count7 += count7
  elif x == 8:
    count8 += count8
  elif x == 9:
    count9 += count9
  elif x == 10:
    count10 += count10
    
 print(count1)
 print(count2)
 print(count3)
 print(count4)
 print(count5)
 print(count6)
 print(count7)
 print(count8)
 print(count9)
 print(count10)

    
    
    
    
    
    

【问题讨论】:

  • 你的打印语句不应该在elif内缩进
  • 我改变了它,我得到了:“for x in range(1,x1): TypeError: only integer scalar arrays can be convert to a scalar index”
  • 您想将 12 算作 1 和 2 的出现吗?还是仅出现 12 次?范围的限制是什么?
  • x1 不是 python int 而是 numpy.int32。它们的行为不同,这就是为什么你不能 range(x1) 没有错误。

标签: python numpy random


【解决方案1】:

您的代码有“countX += countX”,而这两个都是零 - 所以您总是只是将零加在一起。你想要“countX += 1”。

对于您的打印,请使用 print(str(countX)) 并确保它没有缩进(不确定上面是否只是格式化)

但除此之外,我认为这段代码并没有达到你想要的效果。您只是在 1 到 10 之间选择一个数字,然后从 1 循环到比该数字小 1 并进行计数。例如,如果您的随机数是 5,您的结果将是: 1 1 1 1 0 0 0 0 0 0.

您想定义循环运行的次数并在循环中每次随机化数字

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 2023-03-12
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多