1

I Have a query about a nested for loop result.

Code

dieCount = [0,0,0,0,0,0,0,0,0,0,0]

Die1 = random.randint(1,10)
dieCount[Die1] = dieCount[Die1] + 1

Die2 = random.randint(1,10)
dieCount[Die2] = dieCount[Die2] + 1

Die3 = random.randint(1,10)
dieCount[Die3] = dieCount[Die3] + 1


print ("Dice Roll Stats:")
index = 1
print ("\nFace Frequency")
while index < (len(dieCount)):
    print (index)
    for number in range(dieCount[index]):
        print ("*")
    index = index + 1 

Result:

Face Frequency
1
2
3
4
*
5
6
*
7
8
9
*
10

For the life of me i cant figure out how to get a result like such:

Face Frequency
1
2
3
4*
5
6*
7
8
9*
10

If not an answer please guide me to the rite material so I may read through it, I have attempted many different alteration of the code but I still haven't com-up with a decent result. I can use print ("*",end='') but that will append the * before the number. Like wise I tried something like print (index,"*") and then del dieCount[Die1] etc.. to remove the duplicate numbers however that will remove the number completely out of the list.

4

2 回答 2

1

您不需要嵌套循环。您可以使用字符串乘法并将其附加到初始打印语句的末尾,如下所示:

while index < (len(dieCount)):
    print (str(index) + "*" * dieCount[index])
    index += 1
于 2013-05-04T02:32:07.673 回答
1

尝试这个:

index = 1
print ("\nFace Frequency")
while index < (len(dieCount)):
    output = str(index)
    for number in range(dieCount[index]):
        output += "*"
    print(output)
    index = index + 1 

但是我会这样写:

import random

dieCount = [0]*10

for i in range(3):
    dieCount[random.randint(0,9)] += 1

for i,v in enumerate(dieCount):
    print(str(i) + v * '*')

请注意,您的代码有一个错误,您的列表初始化为 11 个零,但您的随机数仅产生 10 个可能的数字。Python 中的列表索引从 0 开始,因此您一直缺少列表的第一项。

于 2013-05-04T02:33:07.863 回答