Python 如何从每个for循环打印唯一的值?
免责声明;我大约一周前才学会Python,所以请原谅我的语法和诸如此类的错误 我用Python尝试了一个小程序,它掷6个骰子并一直运行直到得到6个6。然后计算所需的卷数。这进行得很顺利,但是,我决定让用户决定这个过程重复多少次,并将每个需要的卷数添加到列表中 我的问题是,例如,如果我让程序运行3次,那么最后的列表包含需要3次的最后转鼓数,而不是3个唯一的值Python 如何从每个for循环打印唯一的值?,python,Python,免责声明;我大约一周前才学会Python,所以请原谅我的语法和诸如此类的错误 我用Python尝试了一个小程序,它掷6个骰子并一直运行直到得到6个6。然后计算所需的卷数。这进行得很顺利,但是,我决定让用户决定这个过程重复多少次,并将每个需要的卷数添加到列表中 我的问题是,例如,如果我让程序运行3次,那么最后的列表包含需要3次的最后转鼓数,而不是3个唯一的值 import random as rd rollsum = 0 rollno = 0 n=int(input("How many time
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)
代码早期失败的原因是,在第一次之后,
rollsum
为36,因此它没有进入内部循环。第二件事是,rollno
保留了之前的计数。因此,我的改变是在外部循环中初始化,而不是在外部循环中初始化。jfye:dices=random.choices(范围(1,7),6)
和rollsum=sum(dices)
和print(“Roll:,*dices)
(您从不打印dicesf
btw)您需要为每个“拾取”重置掷骰的数量,因此rollno=0
应在期间移动到上方。因此,应该rollsum=0
,因为您还需要重置“匹配目标”。或者,您可以使用while True
和如果rollsum==36:break
(基本上是一个do…while循环)。每个人都曾经是新手:)
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)