问题描述
我需要用python编写一个程序,该程序可以从1-100生成十个随机数,并使用循环将其存储在列表中.然后,第二个循环应显示所述列表,然后计算偶数和奇数元素的总和以显示它们.到目前为止,这是我所拥有的,非常感谢您的帮助.谢谢
I need to make a program in python that generates ten random numbers from 1-100 that stores it in a list using a loop. Then a second loop should display said list, then calculate the sums of the even and odd elements to display them. This is what I have so far, any help is greatly appreciated. Thanks
import random
def main():
numlist = [0] * 10
for r in range(10):
numlist[r] = random.randint(1,100)
print(numlist)
list_length = len(numlist)
print('The number of elements in the list is', list_length)
更具体地说,这是我坚持的部分.我必须添加奇数元素和偶数元素的总和.我尝试过的每项工作都只给了我全部元素的总和.
More specifically this is the part I'm stuck on. I have to add the sums of the odd and then even elements. Every work around I've tryed has only given me the sum of the total elements.
for x in range(0, 10, 2):
numlist[x] = numlist
print('The Sum of the odd numbers is ', sum(numlist))
main()
推荐答案
import random
nums = [random.randint(1,100) for _ in range(10)]
您可以使用lambda和filter
You can use lambdas and filter
evenSum = sum(filter(lambda i : i%2 == 0, nums))
oddSum = sum(filter(lambda i : i%2, nums))
或进行一些快速帮助功能
Or make some quick helper functions
def isEven(x):
return x % 2 == 0
def isOdd(x):
return x % 2 == 1
evenSum = sum(filter(isEven, nums))
oddSum = sum(filter(isOdd, nums))
这篇关于(Python)坚持跳过randint列表的总和的范围值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!