Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python计算数字在随机列表中重复的次数_Python_Python 3.x - Fatal编程技术网

Python计算数字在随机列表中重复的次数

Python计算数字在随机列表中重复的次数,python,python-3.x,Python,Python 3.x,我已经生成了一个从1到100的随机数列表,我想计算一下重复的次数。例如[1,2,2,3,3,4]有1个额外的2和2个额外的3,所以有3次重复。我希望在不使用任何类型的函数的情况下实现这一点 以下是我的尝试: import random counter = 0 compList = [] num = random.randint(0,100) for i in range(0,100): comp_num = random.randint(0,100) compList.append(

我已经生成了一个从1到100的随机数列表,我想计算一下重复的次数。例如[1,2,2,3,3,4]有1个额外的2和2个额外的3,所以有3次重复。我希望在不使用任何类型的函数的情况下实现这一点

以下是我的尝试:

import random

counter = 0
compList = []
num = random.randint(0,100)

for i in range(0,100):
  comp_num = random.randint(0,100)
  compList.append(comp_num)

  print(compList)
  print(counter)

在添加之前,只需检查该号码是否已在列表中

import random

counter=0
compList=[]

for i in range(100): # don't need range(0,100)...zero is implied.
    comp_num=random.randint(0,100)
    if comp_num in compList: # if number is already in list count it as a repetition.
        counter += 1
    compList.append(comp_num)

# don't indent this under the for loop
print(sorted(compList)) # sorted so you can check the result.
print('repititions:',counter)

从您的评论中,我了解到您希望列表中的元素计数等于上一个元素。这等于列表中元素的数量减去列表中不同元素的数量。如果compList是您填写后的列表,那么您需要

repetitions_count = len(compList) - len(set(compList))
因为集合只包含列表中每个值的一个副本

在您的示例compList=[1,2,2,3,3,4]中,结果是3,如所需

顺便说一句,还有另一种创建列表的方法更快、更短、更具python风格,即oneliner:

compList = [random.randint(0,100) for v in range(0,100)]

请阅读。谢谢你的输入标记,但我真的需要一个关于这个问题的答案。这不是一个为我写代码的网站。写一些代码,展示你的结果,展示你真正想要的。另外,听起来你只是希望有人帮你做作业。好的,我已经用我的代码标记更新了帖子。其次,这不是作业,我正在尝试自己学习。非常感谢,这确实澄清了我的理解。@Daniel,不客气。因此,通过向上投票和/或通过勾选答案旁边的标记选择最有用的答案作为最有用的答案来表示感谢。