Add number, then tuple to list as a tuple, but it drops outer tuple

This question already has an answer here:

  • Difference between append vs. extend list methods in Python 22 answers

  • 使用append:

    l1 = []
    t1 = (1.0 , (2.0,3.0))
    l1.append((t1))
    t2 = (4.0 , (5.0,6.0))
    l1.append(t2)
    print(l1)
    
    l2 = [(1.0, (2.0,3.0)),
          (4.0, (5.0,6.0))]
    print(l2)
    

    Changing it to append() does the trick.

    l1 = []
    t1 = (1.0 , (2.0,3.0))
    l1.append((t1))
    t2 = (4.0 , (5.0,6.0))
    l1.append(t2)
    print(l1)
    
    l2 = [(1.0, (2.0,3.0)),
          (4.0, (5.0,6.0))]
    print(l2)
    

    l1 - [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]

    l2 - [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]

    Append adds the data structure as is to the end of the list, extend extracts the iterables. To understand it better append vs. extend


    You can do it using both extend() and append() . The problem with your code using extend() is that Python does not recognize () as a tuple, even if there is only one element in it. However, it does recognize (,) as an empty tuple:

    l1 = []
    t1 = (1.0 , (2.0,3.0))
    # Note the extra comma
    l1.extend((t1,))
    t2 = (4.0 , (5.0,6.0))
    # Note the extra enclosing parentheses and comma
    l1.extend((t2,))
    print(l1)
    
    l2 = [(1.0, (2.0,3.0)),
          (4.0, (5.0,6.0))]
    print(l2)
    

    The other way, as Vedang Mehta has said, is to use append:

    l1 = []
    t1 = (1.0 , (2.0,3.0))
    l1.append(t1)
    t2 = (4.0 , (5.0,6.0))
    l1.append(t2)
    print(l1)
    
    l2 = [(1.0, (2.0,3.0)),
          (4.0, (5.0,6.0))]
    print(l2)
    

    Both will give you the result of:

    [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]
    [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]
    
    链接地址: http://www.djcxy.com/p/22566.html

    上一篇: 保存程序运行时对列表所做的更改

    下一篇: 添加数字,然后将元组列举为元组,但它会删除外部元组