简体   繁体   English

从 randint 循环中获取总和

[英]Getting Sum from a randint loop

I would like to get the sum of the random numbers produced by my loop This is my loop我想得到循环产生的随机数的总和 这是我的循环

for i in range(1, rolls + 1):
    random1 = str([random.randint(1, 6)])
    print(f'Roll {i}:' + random1)
The output looks like this 
Roll 1:[2]
Roll 2:[5]
Roll 3:[1]
Roll 4:[1]
Roll 5:[2]
Roll 6:[4]
Roll 7:[2]
Roll 8:[5]
Roll 9:[1]
Roll 10:[6]

How do i get the sum from the [brackets]?我如何从 [括号] 中获得总和?

Using a variable to keep track of the sum:使用变量来跟踪总和:

total = 0
for i in range(1, rolls + 1):
    n = random.randint(1, 6)
    total += n
    print(f'Roll {i}: [{n}]')

print(f"Total: {total}")

Using sum :使用sum

nums = [random.randint(1, 6) for i in range(1, rolls + 1)]

for i, n in enumerate(nums):
     print(f'Roll {i}: [{n}]')

print(f"Total: {sum(nums)}")

Alternatively, here's a slightly shorter approach using the := operator in 3.8+:或者,这里有一个在 3.8+ 中使用:=运算符的更短的方法:

total = 0

for i in range(1, rolls + 1):
    total += (n := random.randint(1, 6))
    print(f'Roll {i}: [{n}]')

print(f"Total: {total}")
sum = 0
for i in range(1, rolls + 1):
    rand = random.randint(1, 6)
    sum += rand
    random1 = str(rand)
    print(f'Roll {i}:' + random1)
print(sum)

You can define a variable that adds up all the random numbers您可以定义一个将所有随机数相加的变量

sum_number = 0
for i in range(1, rolls + 1):
    random_number = random.randint(1, 6)
    random1 = str([random_number])
    print(f'Roll {i}:' + random1)
    sum_number += random_number
print(sum_number)

Or you could rewrite it或者你可以重写它

random_number_list = [random.randint(1, 6) for _ in range(rolls)]
sum_number = sum(random_number_list)
# print random number
for i,random_number in enumerate(random_number_list):
    print(f'Roll {i+1}:' + random1)
print(sum_number)

If you don't need to see the print, you just need the first two lines of code如果不需要看打印,只需要前两行代码

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

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