首页 文章

在Python中将整数附加到列表的开头

提问于
浏览
296

我有一个整数和一个列表 . 我想创建一个以变量开头并以列表结尾的新列表 . 写 a + list 我收到错误 . 编译器将 a 作为整数处理,因此我不能使用append或extend . 你会怎么做?

5 回答

  • 417
    >>> a = 5
    >>> li = [1, 2, 3]
    >>> [a] + li  # Don't use 'list' as variable name.
    [5, 1, 2, 3]
    
  • 434
    >>>var=7
    >>>array = [1,2,3,4,5,6]
    >>>array.insert(0,var)
    >>>array
    [7, 1, 2, 3, 4, 5, 6]
    

    这个怎么运作:

    array.insert(index, value)

    在给定位置插入项目 . 第一个参数是要插入的元素的索引,因此 array.insert(0, x) 插入列表的前面, array.insert(len(array), x) 等效于 array.append(x) . 将负值视为相对于数组的末尾 .

  • 34

    请注意,如果您经常尝试执行该操作,尤其是在循环中, a list is the wrong data structure .

    列表未针对前面的修改进行优化, somelist.insert(0, something)O(n) operation .

    somelist.pop(0)del somelist[0] 也是O(n)操作 .

    要使用的正确数据结构是 collections 模块中的deque . deques暴露了一个类似于列表的接口,但是针对来自两个 endpoints 的修改进行了优化 . 他们有一个 appendleft 方法在前面插入 .

    演示:

    In [1]: lst = [0]*1000
    In [2]: timeit -n1000 lst.insert(0, 1)
    1000 loops, best of 3: 794 ns per loop
    In [3]: from collections import deque
    In [4]: deq = deque([0]*1000)
    In [5]: timeit -n1000 deq.appendleft(1)
    1000 loops, best of 3: 73 ns per loop
    
  • 65

    另一种做同样的方式,

    list[0:0] = [a]
    
  • -1

    只需将列表添加到一起即可创建新列表 .

    list1 = ['value1','value2','value3']
    list2 = ['value0']
    newlist=list2+list1
    print(newlist)
    

相关问题