首页 > 解决方案 > 如何获得一个对称的子列表,然后得到该子列表的总和?

问题描述

代码的作用:将整数的 Python 列表作为输入并搜索列表的“对称”内部部分,然后获取该内部部分并获取其总和。

如果列表开头的第 i 个元素的值等于列表末尾的第 i 个元素的值,则对称发生。

我想要的例子:

symmetrical_sum([10,11,12,11,12]) == ([11, 12, 11], 34)
symmetrical_sum([9,99,88,8,77,7,77,8,88,10,100]) == ([88, 8, 77, 7, 77, 8, 88], 353)
symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37) 

是否有任何短编码解决方案来获得上面给出的示例中的输出?我有一个正确的编码版本,但它有 30 多行代码,想知道是否有更短的方法。

标签: pythonlistinteger

解决方案


def symmetrical_sum(a):
    dup=[x for n, x in enumerate(a) if x in a[:n]] #to get the duplicate
    
    to_int = int(''.join(map(str,dup))) #change duplicate into int
    dup1_index=a.index(to_int) #index the first duplicate
    dup2_index=a.index(to_int,dup1_index+1) #index the second duplicate
    portion=a[dup1_index:dup2_index+1] #get the symetric portion
    total = sum(portion) #sum the elements in portion
    tuple1 = (portion,total) #create tuple
    return tuple1

推荐阅读