![](/img/trans.png)
[英]python summing elements in list: first + last, from last to first
[英]summing the first and last elements of list
我想將列表的第一個元素和最后一個元素相加,然后排除這兩個數字並再次重復該過程,直到列表中只有一個元素。 像這樣:
[5,4,3,2,1,6]
[11,5,5]
[16,5]
[21]
我使用了一些方法,但沒有奏效。 我只是一個開始學習 python 的計算機科學專業的學生,所以請大家幫幫我。 謝謝你。
這個答案的主要邏輯是圍繞len of last list print
。 讓我們分成幾點:
邏輯:
1.基本上我們需要first-ith
和last-ith
值的總和,因為我們使用了這個代碼:
l_u[-1][i] + l_u[-1][-i - 1]
2.僅當lenght of last append list
odd-length
even
,上述點才有效,我們必須 append 僅在偶數位置:
l_u[-1][i]
3.在上述兩個要true
的陳述中,這是由這個條件完成的:
len(l_u[-1])%2 != 0 and i%2 != 0
代碼:
l = [5, 4, 3, 2, 1, 6]
l_u = [l]
condn = True
j = 0
while condn:
l_u.append([
l_u[-1][i] if len(l_u[-1]) % 2 != 0 and i % 2 != 0 else l_u[-1][i] +
l_u[-1][-i - 1] for i in range(
len(l_u[-1]) // 2 if len(l_u[-1]) % 2 == 0 else len(l_u[-1]) // 2 +
1)
])
if len(l_u[-1]) <= 1:
break
print(l_u)
OUTPUT:
[[5, 4, 3, 2, 1, 6], [11, 5, 5], [16, 5], [21]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.