我如何预先一个整数到一个列表的开始?

[1, 2, 3]  ⟶  [42, 1, 2, 3]

当前回答

>>> x = 42
>>> xs = [1, 2, 3]
>>> [x] + xs
[42, 1, 2, 3]

注意:不要使用list作为变量名。

其他回答

可以通过简单地将列表添加在一起来生成新的列表。

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

这些对我都没用。我将第一个元素转换为一个系列(单个元素系列)的一部分,并将第二个元素转换为一个系列,并使用append函数。

l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()

选择:

>>> from collections import deque

>>> my_list = deque()
>>> my_list.append(1)       # append right
>>> my_list.append(2)       # append right
>>> my_list.append(3)       # append right
>>> my_list.appendleft(100) # append left
>>> my_list

deque([100, 1, 2, 3])

>>> my_list[0]

100

【注意】:

collections.deque在循环中比Python纯列表更快。

>>> x = 42
>>> xs = [1, 2, 3]
>>> [x] + xs
[42, 1, 2, 3]

注意:不要使用list作为变量名。

另一种方法是,

list[0:0] = [a]