简体   繁体   English

如何从每个 for 循环中打印唯一值?

[英]How to print unique values from each for loop?

Disclaimer;免责声明; I have only picked up Python a week ago or so, so excuse me for any bad syntax and stuff like that.我大约一周前才拿起 Python,所以请原谅我有任何不好的语法和类似的东西。

I have attemped a little program in Python which roll 6 dices and keeps going until it gets 6 sixes.我在 Python 中尝试了一个小程序,它掷出 6 个骰子并继续运行,直到得到 6 个六。 It then counts the number of rolls needed.然后它计算所需的卷数。 This went well, however, i've decided to let the user decide how many times this process is repeated, and add each number of rolls needed to a list.这很顺利,但是,我决定让用户决定这个过程重复多少次,并将每个需要的卷数添加到列表中。

My problem is that if i for an example let the program run 3 times, the list in the end contain the LAST number of rolls needed 3 times, instead of 3 unique values.我的问题是,例如,如果我让程序运行 3 次,最后的列表包含 3 次所需的最后卷数,而不是 3 个唯一值。

import random as rd

rollsum = 0
rollno = 0
n=int(input("How many times do you want to roll 6 sixes?"))
g=[]

for _ in range(n):
    while rollsum != 36:
        a, b, c, d, e, f = (rd.randint(1, 6) for k in range(6))  # The die get assigned a random value between 1 and 6
        rollsum = a + b + c + d + e + f  # The sum of the die is calculated
        rollno += 1  # The number of rolls is increased by 1
        print()
        print("Roll:", a, b, c, d, e)  # Prints the value of each of the 6 die
        print("Sum:", rollsum)  # Prints the sum of the 6 sie
        print("Roll number:", rollno)  # Prints the number of rolls
    g.append(rollno)

print(g)    
import random as rd

n=int(input("How many times do you want to roll 6 sixes?"))
g=[]

for i in range(n):
    rollno = 0
    rollsum = 0
    while rollsum != 36:
        a, b, c, d, e, f = (rd.randint(1, 6) for k in range(6))  # The die get assigned a random value between 1 and 6
        rollsum = a + b + c + d + e + f  # The sum of the die is calculated
        rollno += 1  # The number of rolls is increased by 1
        print()
        print("Roll:", a, b, c, d, e)  # Prints the value of each of the 6 die
        print("Sum:", rollsum)  # Prints the sum of the 6 sie
        print("Roll number:", rollno)  # Prints the number of rolls
    g.append(rollno)

print(g)    

The reason your code failed ealier is that after the first time, rollsum was 36 and therefore it didn't enter the inner loop.您的代码较早失败的原因是,在第一次之后, rollsum为 36,因此它没有进入内部循环。 The second thing was that rollno kept the previous count.第二件事是rollno保留了之前的计数。 So my change was to initialize both in the outer loop and not outside.所以我的改变是在外部循环而不是外部进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM