在 Python 中将整数附加到列表的开头 [英] Append integer to beginning of list in Python

查看:39
本文介绍了在 Python 中将整数附加到列表的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数和一个列表.我想制作一个以变量开头并以列表结尾的新列表.编写 a + list 出现错误.编译器将 a 作为整数处理,因此我不能使用附加或扩展.你会怎么做?

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. The compiler handles a as integer, thus I cannot use append, or extend either. How would you do this?

推荐答案

>>>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).负值被视为相对于数组的末尾.

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.

这篇关于在 Python 中将整数附加到列表的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆