这是大学作业。我必须模拟10次随机骰子滚动(1 - 6),并将它们放在一个列表中,然后创建另一个列表,该列表将保留每个值滚动的次数。我的输出必须像这样:
Your rolls: [6, 2, 3, 4, 5, 6, 3, 1, 5, 2]
Number of rolls:
1 -> 1
2 -> 2
3 -> 2
4 -> 1
5 -> 2
6 -> 2
我的代码是这样的:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = []
print(f"Your rolls: {rolls}")
print("Number of rolls:")
rolls.sort()
for i in rolls:
# Puts the amount of times each number (1-6) rolled inside roll_count
roll_count.append(rolls.count(i))
# Removes the duplicates so that the count doesn't register again
while rolls.count(i) > 1:
rolls.remove(i)
for n in range(1, 7):
# Checks if the possible rolls (1-6) have been rolled, if not place the count as 0
# in the sorted index inside roll_count
if n not in rolls:
roll_count.insert(n - 1, 0)
print(f"{n} -> {roll_count[n - 1]}")
它工作正常,但我想知道我是否可以使它更有效,甚至简化它。
这类任务的标准工具是来自标准库的collections.Counter
。它是专门为这项任务而建造的。
from collections import Counter
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = Counter(rolls)
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for n in range(1, 7):
print(f"{n} -> {roll_count[n]}")
Your rolls: [2, 5, 3, 3, 3, 2, 5, 5, 2, 6]
Number of rolls:
1 -> 0
2 -> 3
3 -> 3
4 -> 0
5 -> 3
6 -> 1
如果由于某种原因您不允许使用collections.Counter()
,那么您的实现就像它可以一样好,只有一个例外-dict
是比list
更好的数据结构用于滚动计数(实际上,collections.Counter
是dict
的子类)。这使您能够使用setdefault()
和get(key, default)
,从而减少了几行代码:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = {}
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for i in rolls:
roll_count.setdefault(i, 0) # does nothing if element is already present
roll_count[i] += 1
for n in range(1, 7):
print(f"{n} -> {roll_count.get(n, 0)}")
from random import randint
rolls = []
roll_count = [0] * 6
for i in range(10):
r = randint(1,6)
rolls.append(r)
roll_count[r-1] = roll_count[r-1] + 1
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for n in range(1, 7):
print(f"{n} -> {roll_count[n - 1]}")
不是循环一次形成一个滚动列表,然后再循环一次计数每一个,你可以这样做,循环一次,滚动和计数在同一个循环。你也不需要排序或检查计数是否存在。
由于值的范围如此有限,因此不需要使用任何花哨的集合来跟踪它们,当然也不需要对输入进行排序。一个简单的list
就可以了,初始化为全零。
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = [0] * 6
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for i in rolls:
# Puts the amount of times each number (1-6) rolled inside roll_count
roll_count[i - 1] += 1
for n in range(1, 7):
print(f"{n} -> {roll_count[n - 1]}")
Your rolls: [4, 1, 3, 3, 4, 3, 4, 5, 2, 2]
Number of rolls:
1 -> 1
2 -> 2
3 -> 3
4 -> 3
5 -> 1
6 -> 0