Python如何使用while/for循环和break语句找到列表[7,5,4,4,3,1,-2,-3,-5,-7]中所


given_list5=[7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7=0
i = 0
while True:
if given_list5[i] >=0:
break
total7 += given_list5[i]
i += 1
print(total7)

这是我的密码。请帮我修一下。谢谢。

given_list5=[7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total_neg=0
for i in given_list5:    #that means you select every item in the list by one by. it's a loop
if i<0:
total_neg+=i     #that means total_neg=total_neg + i
print(total_neg)

for num in given_list5:loop given_list5元素

str.isdigit()(检查数字(:True=str,False:数字

given_list5=[7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
sumNegativeQuantity = 0
for num in given_list5 :
if (str(num).isdigit() == False) and (num < 0) :
sumNegativeQuantity += num  
print(sumNegativeQuantity)

结果

-17

Python允许单行循环约定。同样,对于这样的事情,你可以简单地做:

given_list5 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
filtered_list5 = [i for i in given_list5 if i < 0]
total7 = sum(filtered_list5)
print(total7)
>> -17

说明:filtered_list5只过滤负数列表,sum()计算列表中所有元素的和。

将所有内容组合在一行中:total7 = sum([i for i in given_list5 if i < 0])

EDIT查看@Nick提到的OP的代码风格,这里有一个使用的实现

a(for-loop

given_list5 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
for number in given_list5:
if number < 0:
total7 += number

print(total7)
>> -17

b( 如果你是一个初学者,while-loop实际上是很棘手的。要使用while循环循环列表,您必须在列表上使用内置函数.pop()。你可以检查一下这个解释。因此,在您的代码上,实现将是:

given_list5 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
while given_list5:
number = given_list5.pop()
if number < 0:
total7 += number

print(total7)
>> -17
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total6 = 0
for element in given_list3:
if element >= 0:
continue
total6 += element
print(total6)
>> -17

最新更新