过滤和控制for循环列表中要求的项数 - Python

时间:2017-10-02 05:28:30

标签: python for-loop filter

我是Python新手而且卡住了。我怎么写这个? "写一个for循环来对前10个非零整数求和"

2 个答案:

答案 0 :(得分:0)

一步一步地采取行动:

# example list of 14 elements, 11 elements are non-zero 
mylist = [0, 4, 17, 2, 14, 3, 8, 0, 2, 1, 0, 7, 5, 5] 
# non-zero   1   2  3   4  5  6     7  8     9 10  

# initialize variables
mysum = 0 
count = 1 # counter until we get to 10

for x in mylist:                # for each item in the list
    if x != 0 and count <= 10:  # if both conditions are satisfied
        mysum += x              # add the item to the sum
        count += 1              # increase the counter until we reach 10

print mysum

输出:

63

对于这个例子,它排除了最后的5,因为我们只考虑前10个非零元素

答案 1 :(得分:0)

如果列表在第10个非零整数之后并没有那么大,那么我会删除所有的零,并在前10个数字的切片上调用sum:

mylist = [0, 4, 17, 2, 14, 3, 8, 0, 2, 1, 0, 7, 5, 5] 

total = sum([ n for n in mylist if n > 0 ][:10])
print(total)