[英]How to print frequency of each unique word from a string with for loop in python
[英]How to print unique values from each for loop?
免责声明; 我大约一周前才拿起 Python,所以请原谅我有任何不好的语法和类似的东西。
我在 Python 中尝试了一个小程序,它掷出 6 个骰子并继续运行,直到得到 6 个六。 然后它计算所需的卷数。 这很顺利,但是,我决定让用户决定这个过程重复多少次,并将每个需要的卷数添加到列表中。
我的问题是,例如,如果我让程序运行 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)
您的代码较早失败的原因是,在第一次之后, rollsum
为 36,因此它没有进入内部循环。 第二件事是rollno
保留了之前的计数。 所以我的改变是在外部循环而不是外部进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.