(Python)坚持跳过randint列表总和的范围值

时间:2014-10-08 19:42:27

标签: python loops random range

我需要在python中创建一个程序,该程序从1-100生成10个随机数,使用循环将其存储在列表中。然后第二个循环应显示所述列表,然后计算偶数和奇数元素的总和以显示它们。这是我到目前为止,任何帮助都非常感谢。感谢

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)

更具体地说,这是我坚持的部分。我必须添加奇数和偶数元素的总和。我尝试过的每一项工作都只给了我总元素的总和。

    for x in range(0, 10, 2):
        numlist[x] = numlist 

    print('The Sum of the odd numbers is ', sum(numlist))


main()

3 个答案:

答案 0 :(得分:2)

import random
nums = [random.randint(1,100) for _ in range(10)]

您可以使用lambdas和filter

evenSum = sum(filter(lambda i : i%2 == 0, nums))
oddSum = sum(filter(lambda i : i%2, nums))

或制作一些快速帮助函数

def isEven(x):
    return x % 2 == 0

def isOdd(x):
    return x % 2 == 1

evenSum = sum(filter(isEven, nums))
oddSum = sum(filter(isOdd, nums))

答案 1 :(得分:1)

使用您自己的代码:

def main():
    numlist = [] # create empty list to add randints to 
    for r in range(10):
        numlist.append(random.randint(1,100)) # append to the list
    list_length = len(numlist)
    print('The number of elements in the list is', list_length)
    odd = 0
    even = 0
    for num in numlist:
        if num % 2: # if num mod 2 has a remainder, num is odd
            odd += num
        else:  # else num is even
            even += num
    print('The Sum of the odd numbers is {} and even numbers is {}'.format(odd,even))

您可以使用列表comp替换第一个循环:

numlist = [random.randint(1,100) for _ in range(10)]

答案 2 :(得分:-1)

无法理解实际问题(呵呵呵呵!) 据我所知,你想打印从randint()生成的列表的奇数和偶数之和。我刚刚编辑了你的代码;)

所以这是简单的完成代码!

投票如果它有帮助!

        import random
        def main():
            odd_sum=0
            even_sum=0
            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)

            for i in numlist:
                if (i%2 == 1):            #the remainder is 1 if the number is odd
                    odd_sum = odd_sum + i  #add the odd_numbers
                elif(i%2 == 0):           #the remainder is 0 if the number is even     
                    even_sum = even_sum + i #add the even_numbers
                else:
                    print "No need of this else part !"
            print "Odd_sum = ",odd_sum
            print "Even_sum = ",even_sum
        main()