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

本文探讨如何在Python中将整数添加到列表的开头,指出使用`insert`方法或通过列表相加创建新列表的方式。由于`append`和`extend`不适合此操作,建议在频繁操作列表前端时使用`collections.deque`以提高效率。
摘要由CSDN通过智能技术生成

本文翻译自:Append integer to beginning of list in Python

I have an integer and a list. 我有一个整数和一个列表。 I would like to make a new list of them beginning with the variable and ending with the list. 我想创建一个新的列表,它们以变量开头,以列表结尾。 Writing a + list I get errors. a + list会出错。 The compiler handles a as integer, thus I cannot use append, or extend either. 编译器将a作为整数处理,因此我不能使用append或extend。 How would you do this? 你会怎么做?


#1楼

参考:https://stackoom.com/question/1D9UZ/在Python中将整数附加到列表的开头


#2楼

>>> a = 5
>>> li = [1, 2, 3]
>>> [a] + li  # Don't use 'list' as variable name.
[5, 1, 2, 3]

#3楼

>>>var=7
>>>array = [1,2,3,4,5,6]
>>>array.insert(0,var)
>>>array
[7, 1, 2, 3, 4, 5, 6]

How it works: 怎么运行的:

array.insert(index, value)

Insert an item at a given position. 在给定位置插入项目。 The first argument is the index of the element before which to insert, so array.insert(0, x) inserts at the front of the list, and array.insert(len(array), x) is equivalent to array.append(x) .Negative values are treated as being relative to the end of the array. 第一个参数是要插入元素的索引,因此array.insert(0, x)插入列表的最前面,而array.insert(len(array), x)等效于array.append(x) 。负值被视为相对于数组的末尾。


#4楼

另一种方式,

list[0:0] = [a]

#5楼

Note that if you are trying to do that operation often, especially in loops, a list is the wrong data structure . 请注意,如果您尝试经常执行该操作,尤其是在循环中,则列表是错误的数据结构

Lists are not optimized for modifications at the front, and somelist.insert(0, something) is an O(n) operation . 列表未针对前端的修改进行优化, somelist.insert(0, something)O(n)操作

somelist.pop(0) and del somelist[0] are also O(n) operations. somelist.pop(0)del somelist[0]也是O(n)运算。

The correct data structure to use is a deque from the collections module. 正确使用的数据结构是来自collections模块的deque deques expose an interface that is similar to those of lists, but are optimized for modifications from both endpoints. deques公开了与列表类似的接口,但针对两个端点的修改进行了优化。 They have an appendleft method for insertions at the front. 他们在前面有一个appendleft方法用于插入。

Demo: 演示:

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

#6楼

New lists can be made by simply adding lists together. 只需将列表加在一起即可创建新列表。

list1 = ['value1','value2','value3']
list2 = ['value0']
newlist=list2+list1
print(newlist)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值