我正在尝试使用我的create_list在1-6之间生成10,000个数字。 count_list假设计算生成的1,2,3,4,5,6的数量,主函数假设附加两个,然后打印每个的结果。顺便说一下,我刚开始使用def,所以对我很轻松;)
def count_list(my_list, c):
amount_one=0
amount_two=0
amount_three=0
amount_four=0
amount_five=0
amount_six=0
or number in my_list:
if number==1:
amount_one+=1
elif number==2:
amount_two+=1
elif number==3:
amount_three+=1
elif number==4:
amount_four+=1
elif number==5:
amount_five+=1
elif number==6:
amount_six+=1
return amount_one
return amount_two
return amount_three
return amount_four
return amount_five
return amount_six
def create_list(n):
import random
my_list=[]
for i in range(10000):
n=random.randint(1,6)
my_list.append(n)
return my_list
def main():
hello=count_list(create_list)
print "1-",count_list()[0]
print "2-",count_list()[1]
print "3-",count_list()[2]
print "4-",count_list()[3]
print "5-",count_list()[4]
print "6-",count_list()[5]
main()
答案 0 :(得分:3)
您可以使用参数n
来确定列表中要生成的数字数
def create_list(n):
import random
my_list = []
for i in range(n):
my_list.append(random.randint(1,6))
return my_list
要计算列表中的项目,一个直接的方法就是这样
def count_list(l):
c = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0} # initialize dictionary
for key in c:
c[key] = l.count(key)
return c
现在我们可以在main
def main():
nums = create_list(1000)
counts = count_list(nums)
for i in range(1,7):
print(i, counts[i])
测试
>>> main()
1 185
2 166
3 162
4 168
5 143
6 176
为了好玩,这里有一些稍微更先进的方法,以更有效的方式做同样的事情
def create_list(n):
import random
return [random.randint(1,6) for _ in range(n)] # using a list comprehension
def count_list(l):
from collections import Counter # using the Counter class
return Counter(l)
def main():
nums = create_list(1000)
counts = count_list(nums)
for i in range(1,7):
print(i, counts[i])
答案 1 :(得分:2)
使用collections.Counter
进行计数,只需将create_list
返回的数字列表传递给它:
from collections import Counter
import random
def create_list():
my_list = []
for i in range(10000):
n = random.randint(1, 6)
my_list.append(n)
return my_list
print(Counter(create_list()))
Counter({1: 1702, 4: 1695, 6: 1692, 3: 1688, 5: 1651, 2: 1572})
如果您想要3个最常见的数字等,请使用.most_common(3)
:
print(Counter(create_list()).most_common(3))
答案 2 :(得分:0)
您可以使用字典将计数与相应的数字进行映射:
def count_list(my_list):
from collections import defaultdict
dict = defaultdict(int)
for x in my_list:
dict[x] += 1
return dict
def create_list(a,b):
import random
my_list=[]
for i in range(10000):
n=random.randint(a,b)
my_list.append(n)
return my_list
def main():
lst = create_list(1,6)
dict = count_list(lst)
print(dict)
if __name__=="__main__":
main()