繁体   English   中英

如何将列表中的第一个和最后一个元素相加以获得最后的 2 位数字?

[英]How to sum first and last element in list to get 2 digit number in the end?

    x = "jankometka"
    freq = {}
    for c in x:
        freq[c] = x.count(c)
    #print(freq)
    
    empty_list = []
    
    my_list = list(freq.values())
    
    
    
    givenIndices = [0, -1]
    indicesList = sorted(givenIndices, reverse=True)
    sum = my_list[0] + my_list[1]
    for i in my_list:
    
        for indx in indicesList:       
            if indx < len(my_list):           
                my_list.pop(indx)
                empty_list.append(my_list)
    
            print(my_list)
"jankometka" - after counting letter occurrence i got list
    
    [1, 2, 1, 2, 1, 1, 1, 1] - here I want to sum firs and last number in list and should get this
    [2, 3, 2, 3] and than
    [5, 5]
    
    and also i have to remove index 0 and -1 from original list
    [1, 2, 1, 2, 1, 1, 1, 1]
    [2, 1, 2, 1, 1, 1]
    [1, 2, 1, 1]
    [2, 1]

我不知道如何遍历列表,对列表中的第一个和最后一个元素求和,然后删除第一个和最后一个元素,直到我得到两位数。 谢谢你

In [32]: L = [1, 2, 1, 2, 1, 1, 1, 1]

In [33]: answer = []

In [34]: while len(answer) != 1:
    ...:     while L:
    ...:         answer.append(L[0]+L[-1])
    ...:         L = L[1:-1]
    ...:     if len(answer) == 1: break
    ...:     print(answer)
    ...:     L = answer
    ...:     answer = []
    ...:
[2, 3, 2, 3]
[5, 5]

如果您的列表不是太长,递归解决方案可能 -

def rec_sum_ends(lst):
    if len(lst) <= 2:
        return lst
    midpoint = len(lst) // 2
    front_half = lst[:midpoint]
    reversed_back_half = lst[:-midpoint-1:-1]
    combined = [sum(el) for el in zip(front_half, reversed_back_half)]
    return rec_sum_ends(combined)
rec_sum_ends([1, 2, 1, 2, 1, 1, 1, 1])

Output

[5, 5]
def rec_remove_ends(lst):
    if len(lst) <= 2:
        return lst
    return rec_remove_ends(lst[1:-1])
rec_remove_ends([1, 2, 1, 2, 1, 1, 1, 1])

Output

[2, 1]

编辑:处理奇数长度列表

上述解决方案适用于包含偶数项的列表。 根据您对如何处理奇数列表的评论 - 您可以做一些重新工作以将“中间”元素与奇数列表隔离并将其添加回来 -

def both_odd_even_lists(lst):
    if len(lst) % 2 == 0:
        return rec_sum_ends(lst)
    else:
        midpoint = len(lst) // 2
        new_lst = lst[:midpoint] + lst[midpoint+1:]
        mid_item = lst[midpoint]
        reduced_new_lst = rec_sum_ends(new_lst)
        return [reduced_new_lst[0] + mid_item, reduced_new_lst[1]]

Output

# both_odd_even_lists([1, 1, 1, 1, 1, 1, 2, 1, 1])
[5, 5]

暂无
暂无

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

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