【问题标题】:Nested For Loop Result嵌套 For 循环结果
【发布时间】:2013-05-04 02:27:00
【问题描述】:

我有一个关于嵌套 for 循环结果的查询。

代码

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 

结果:

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

对于我的一生,我无法弄清楚如何获得这样的结果:

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

如果没有答案,请指导我阅读仪式材料,以便我可以通读它,我尝试了许多不同的代码更改,但我仍然没有得到一个像样的结果。我可以使用 print ("*",end='') 但这会在数字前附加 *。同样,我尝试了类似 print (index,"*") 然后 del dieCount[Die1] 等的方法来删除重复的数字,但这会将数字完全从列表中删除。

【问题讨论】:

    标签: python python-2.7 python-3.x


    【解决方案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 开始,因此您一直缺少列表的第一项。

    【讨论】:

    • 非常感谢,我试过这样的东西,我一定是写错了。
    【解决方案2】:

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

    while index < (len(dieCount)):
        print (str(index) + "*" * dieCount[index])
        index += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多