简体   繁体   English

将列表的第一个和最后一个元素相加

[英]summing the first and last elements of list

I'd like to sum the first element and last elements of a list, and then exclude those two numbers and repeat that process again until there is only one element in the list.我想将列表的第一个元素和最后一个元素相加,然后排除这两个数字并再次重复该过程,直到列表中只有一个元素。 Like this:像这样:

[5,4,3,2,1,6]
[11,5,5]
[16,5]
[21]

I used some methods but didn't work.我使用了一些方法,但没有奏效。 I am just a computer science student starting to python so help me out please guys.我只是一个开始学习 python 的计算机科学专业的学生,所以请大家帮帮我。 Thank you.谢谢你。

Main logic of this answer is revolve around len of last list print .这个答案的主要逻辑是围绕len of last list print Lets break it in few points:让我们分成几点:

LOGIC:逻辑:
1. Basically we need sum of first-ith and last-ith value for that we used this code: 1.基本上我们需要first-ithlast-ith值的总和,因为我们使用了这个代码:

l_u[-1][i] + l_u[-1][-i - 1]

2. Above point is only valid when lenght of last append list is even for odd-length we have to append this only at even poistion: 2.仅当lenght of last append list odd-length even ,上述点才有效,我们必须 append 仅在偶数位置:

l_u[-1][i]  

3. Among above two statement which is going to true this is done by this condition: 3.在上述两个要true的陈述中,这是由这个条件完成的:

len(l_u[-1])%2 != 0 and i%2 != 0

CODE:代码:

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: OUTPUT:

[[5, 4, 3, 2, 1, 6], [11, 5, 5], [16, 5], [21]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM