簡體   English   中英

如何在python的列表中添加元組

[英]How to add tuples in list in python

我有以下元組列表:

[[(16,)], [(2,)], [(4,)]]

我想總結里面的數字,但沒有這樣做。

我試過了

res = sum(*zip(*resultsingle))

res = sum(map(sum, resultsingle))

但我得到了錯誤

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

我錯過了什么?

也許嵌套理解會起作用:

>>> xss = [[(16,)], [(2,)], [(4,)]]
>>> sum(x for xs in xss for t in xs for x in t)
22

您的列表是嵌套列表。 你有一個包含listlist ,其中包含tuple

這是一個已知的結構。 您可以輕松獲取每個元素並將它們相加。 但是假設您有一個嵌套列表,您不知道其中有多少列表或元組或它們是如何嵌套的?

在這種情況下,您需要展平列表。 意思是,你得到所有不是listtuple的元素,並將它們擴展到一個列表中。 為此,您可以使用遞歸:

def flatten(lst):
    dt = []
    if isinstance(lst, (list, tuple)):
        for each in lst:
            dt.extend(flatten(each))
    else:
        dt.extend([lst])
    return dt


if __name__ == '__main__':
    print(flatten([1, [1, 2], 3, [1, [1, 2]]]))

結果:

[1, 1, 2, 3, 1, 1, 2]

現在你只需要總結一下:

print(sum(flatten([1, [1, 2], 3, [1, [1, 2]]])))

結果:

11

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM