from random import randrange
def roll2dice() -> int:
roll2 = []
for i in range(50):
sum = randrange(1,7) + randrange(1,7)
roll2.append(sum)
return roll2
上述函数用于生成两个骰子的随机滚动和。
def distribution (n: int):
result = []
for x in range(2,13):
result.append(roll2dice())
for x in range(2,13):
dice = result.count(x)
num_of_appearances = result.count(x)
percentage = (result.count(x) / int(n)) * 100
bar = result.count(x)*'*'
print("{0:2}:{1:8}({2:4.1f}%) {3.5}".format(dice, num_of_appearances, percentage, bar))
然后我使用roll2dice创建了一个分发函数,其中
distribution(200)
应该产生:
2: 7 ( 3.5%) *******
3: 14 ( 7.0%) **************
4: 15 ( 7.5%) ***************
5: 19 ( 9.5%) *******************
6: 24 (12.0%) ************************
7: 35 (17.5%) ***********************************
8: 24 (12.0%) ************************
9: 28 (14.0%) ****************************
10: 18 ( 9.0%) ******************
11: 9 ( 4.5%) *********
12: 7 ( 3.5%) *******
然而,错误说:
Traceback (most recent call last):
File "C:/Python34/lab6.py", line 23, in <module>
distribution_of_rolls(200)
File "C:/Python34/lab6.py", line 21, in distribution_of_rolls
print("{:2d}:{1:8d}({2:4.1f}%) {3.5s}".format(dice_num, num_of_appearance, percentage, stars))
ValueError: cannot switch from automatic field numbering to manual field specification
答案 0 :(得分:1)
前3个字段为$j = count($skills_nav)
最后一个字段为{n_field:format}
,不包含字段编号。
以下是您想要做的(我认为)的工作版本:
{3.5}
或者,列表理解:
from random import randrange
def distribution (n: int):
result = []
for x in range(n):
sum = randrange(1,7) + randrange(1,7)
result.append(sum)
for dice in range(2,13):
num_of_appearances = result.count(dice)
percentage = (num_of_appearances / n) * 100
bar = int(percentage) * '*'
print("{0:2}:{1:8} ({2:4.1f}%) {3}".format(dice, num_of_appearances, percentage, bar))