使用for循环以符号形式显示字符串值

2024-05-04 00:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单die_count = [0,0,0,0,0,0,0]; 未使用元素0,因此忽略元素1-6很重要。 所以基本上这些元素都是连接到random.randint的,它会生成一个随机数,在我的程序中,这些数字会在用户使用时多次生成

因此,在我的课程结束时,我需要显示这些统计数据:

Dice Roll Stats:
Face Frequency
 1 *
 2 ***
 3 *
 4 *
 5 **
 6 **

正如你所看到的,列表基本上是骰子的边,星星显示了在程序中该面的生成次数

我试着这样做,但有时代码不执行,有时执行,只显示整数

index = 1
while index < die_count[2] :
    for num in die_count :
        print(num)
        index += 1

Tags: 用户程序元素indexstatscount数字random
2条回答

您可以执行以下操作:

die_count = [0,4,5,3,2,1,7]

for i in range(1, len(die_count)):
    print(i, die_count[i] * "*")

它将输出:

1 ****
2 *****
3 ***
4 **
5 *
6 *******

在什么情况下,您的代码不起作用?这个问题不清楚

还有,如果不使用第一个元素,为什么要用7个元素启动die_count。这没有任何意义

您还可以更高级一点,并使用它允许用户输入决定骰子滚动的次数,而不是显示它

side = 0
diceList = [0]
while side !=6:
    side +=1
    diceCount = int(input(f'How many times did the dice roll on side {side}: '))
    diceList.append(diceCount)
for i in range(1, len(diceList)):
    print(i, diceList[i] * "*")

相关问题 更多 >