问题描述
给定一个列表(按降序)找到所有负数的总和
我可以很容易地用 for
循环解决它:
但是我好像用while
循环解决不了,网上找的所有解决方法都是用的len()
,我还没学会,有没有其他的方法呢???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
解决方法
您可以使用列表索引:l[-1]
会给您列表的最后一个元素,而 l[-2]
是倒数第二个元素,依此类推。可以使用这个想法。由于此列表按降序排列,因此您可以使用 while 循环中的 <
条件确保添加到总数中的元素是负数,然后在找到元素后将其中断要乐观。如果您需要更多线索/帮助,请告诉我! :)
问题列表按降序排序。您可以从最后一个元素开始循环,直到找到等于或大于 0
的元素并中断 while
循环。
使用建议的负索引解决方案,以及给出输入示例,我们需要考虑其他情况:空列表;所有正面清单;所有负面清单。除了添加 try
子句之外,我们可以通过将结束标记强加到测试列表的前面来处理所有这些:
given_list4 = [7,5,4,3,1,-2,-3,-5,-7]
total7 = 0
index = -1
while [0,*given_list4][index] < 0:
total7 += given_list4[index]
index -= 1
print(total7)
显然,最好使用 try
子句。
您可以使用负索引:
given_list4 = [7,-7]
total7 = 0
index = -1
while given_list4[index] < 0:
total7 += given_list4[index]
index -= 1
print(total7)
输出:
-17
数组的 -1
索引是数组的最后一个元素,-2
是倒数第二,-3
是倒数第三,依此类推。
请注意,这仅在列表中至少有一个数字不是负数时才有效,否则会引发索引错误。为避免索引错误,您可以添加
given_list4 = [7,-7]
if given_list4[0] >= 0:
total7 = 0
index = -1
while given_list4[index] < 0:
total7 += given_list4[index]
index -= 1
else:
total7 = sum(given_list4)
这也假设列表不为空。如果列表可能为空,则需要另一个 if
语句:
given_list4 = [7,-7]
if given_list4:
if given_list4[0] >= 0:
total7 = 0
index = -1
while given_list4[index] < 0:
total7 += given_list4[index]
index -= 1
else:
total7 = sum(given_list4)