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

创建列表、追加数据并转换为元组:最短代码[重复]

  •  1
  • toti08  · 技术社区  · 6 年前

    所以基本上我想做的是:

    • 将列表转换为元组

    所以我想我应该这样做:

    anotherList = [2,5,8]
    myTuple = tuple([1,2,3].extend(anotherList))
    

    这不起作用,因为它抛出错误:

    TypeError: 'NoneType' object is not iterable
    

    这是有道理的,因为 extend

    anotherList = [2, 5, 8]
    myList = [1, 2, 3]
    myList.extend(anotherList)
    myTuple = tuple(myList)
    

    3 回复  |  直到 6 年前
        1
  •  3
  •   Martijn Pieters    6 年前

    你不想用 list.extend() ,句号。如果要将列表显示(文字语法)与另一个列表连接起来,请使用 + :

    myTuple = tuple([1, 2, 3] + anotherList)
    

    或者你可以改变信仰 anotherList

    myTuple = (1, 2, 3) + tuple(anotherList)
    

    在这里,Python编译器可以优化和存储 (1, 2, 3) 作为代码对象的常量。初始元组只创建一次,并在所有执行中重用。

    list.extend() 旨在通过对现有列表对象的引用来就地更新该列表对象,但在列表文本上使用它意味着生成的扩展列表没有剩余的引用,将再次被丢弃。

    在python3.5及更高版本中,还可以使用 new iterable unpacking syntax :

    myTuple = (1, 2, 3, *anotherlist)
    

    请注意,没有 tuple() 那里需要电话,而且 任何

        2
  •  3
  •   ForceBru    6 年前

    您可以添加列表:

    result = tuple([1,2,3] + [4,5,6])
    

    所以是这样的:

    anotherList = [2, 5, 8]
    myList = [1, 2, 3]
    
    myTuple = tuple(myList + anotherList)
    
        3
  •  2
  •   U13-Forward    6 年前

    不清楚,但是。。。

    l=[2,5,8]
    print(tuple([1,2,3]+l))
    

    +

    或者你可以 *

    print((*l, 1,2,3))
    

    或者你能做什么 chain itertools :

    import itertools
    print(tuple(itertools.chain(l, [1,2,3])))
    

    merge heapq

    from heapq import merge
    print(tuple(merge(l,[1,2,3])))
    

    或者 add 形式 operator :

    import operator
    print(tuple(operator.add(l, [1,2,3])))