我正在练习 Python 问题并遇到了这个问题,如果元素按递增顺序添加并将它们存储在列表中,我必须在列表中添加元素。
例如:
my_list = [2,223,6,4,10,12,15]
从 2 到 223,列表在增加,然后从 223 到 6,它在减少。因此,总和为 2+223=225。
列表从 223 到 6、6 到 4 减少,从 4 到 10、10 到 12、12 到 15 增加,所以总和是 4+10+12+15=41。
所以,我的 sum_list
将是 [225,41]
。
我试过的代码:
list1 = [2,223,6,4,10,12,15]
current_el = list1[0]
suml=list()
sum1=current_el
for i in list1[list1.index(current_el)+1:]:
while current_el < i:
print(i)
sum1=sum1+i
current_el = list1[list1.index(current_el)+1]
print(current_el)
suml.append(sum1)
print(suml)
答案 0 :(得分:2)
这更简单:
numbers = [2, 223, 6, 4, 10, 12, 15]
accumulated = []
for i in range(1, len(numbers)):
if numbers[i] > numbers[i-1]:
if i == 1 or numbers[i-1] <= numbers[i-2]:
accumulated.append(numbers[i-1])
accumulated[-1] += numbers[i]
使用 if numbers[i] > numbers[i-1]
我们检查一个数字是否大于前一个(增加),使用 accumulated[-1] += numbers[i]
我们将该数字添加到最后一个累积值。现在我们只缺少在累积列表中创建新元素的逻辑,这是当我们找到一个大于前一个的数字但前一次迭代没有通过这个条件或者如果没有前对我们可以查。
另一种与您尝试的解决方案更相似的不同解决方案是分两步完成。第一步将创建一个列表列表,其中的数字按升序分组。然后您丢弃单个成员的那些组(您不考虑 6 作为升序组),然后将这些组添加在一起。
numbers = [2, 223, 6, 4, 10, 12, 15]
groups = [[2]]
for number in numbers[1:]:
if number > groups[-1][-1]:
groups[-1].append(number)
else:
groups.append([number])
accumulated = []
for group in groups:
if len(group) == 1:
continue
accumulated.append(sum(group))