python randint什么分布,(Python)坚持跳过randint列表之和的范围值

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)]

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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值