代码之家  ›  专栏  ›  技术社区  ›  chester

如何将元组中的元素相加?

  •  0
  • chester  · 技术社区  · 4 年前

    我想知道如何将每个元组中的元素添加到一个列表中。这是我的代码:

    def add_together():
    
        list = [(2,3), (4,5), (9,10)]
        for tuple in list:
            #missing code goes here I think.
                print('{} + {} = {}'.format(x,y,a))
    add_together()
    

    我想要的输出将从

    2 + 3 = 5
    

    我该怎么做?

    3 回复  |  直到 4 年前
        1
  •  1
  •   smac89    4 年前

    您可以使用元组拆包语法来获取元组中的每个项:

    def add_together(lst):
        for (x, y) in lst:
            print('{} + {} = {}'.format(x,y,x+y))
    
    lst = [(2,3), (4,5), (9,10)]
    add_together(lst)
    
        2
  •  1
  •   Prashant Kumar    4 年前

    试试这个:

    def add_together():
        input_list = [(2,3), (4,5), (9,10)]
        for tup in input_list:
            #missing code goes here I think.
                print('{} + {} = {}'.format(tup[0],tup[1],tup[0]+tup[1]))
    add_together()
    

    输出

    2 + 3 = 5
    4 + 5 = 9
    9 + 10 = 19
    
        3
  •  1
  •   Алексей Р   4 年前

    还可以使用*来拆包元组

    def add_together():
        list = [(2, 3), (4, 5), (9, 10)]
        for tupl in list:
            print('{} + {} = {}'.format(*tupl, sum(tupl)))
    
    add_together()
    

    打印:

    2 + 3 = 5
    4 + 5 = 9
    9 + 10 = 19