简体   繁体   English

如何将数字添加到列表中的某个索引?

[英]How to add a number to a certain index in a list?

list = [4, 7, 5, 3]

In this list i understand that the number 4 has an index of 0, 7 has 1, 5 has 2 and 3 has 3, but how would i add a value to an individual index? 在此列表中,我知道数字4的索引为0、7的索引为1、5的索引为2、3的索引为3,但是我如何为单个索引添加值?

(list[1] + 1)

I thought that the above would would make it so that when i print the list it would give: 我认为以上将使它,以便当我打印列表时将给出:

print(list)

[4, 8, 5, 3]

You need to do (you weren't actually giving a value with = , so once you did the addition the result was just thrown away): 您需要这样做(实际上并没有使用=给出值,所以一旦完成加法,结果就被丢弃了):

list[1] += 1  # Short for list[1] = list[1] + 1

Integers are immutable , so you can't modify them in place. 整数是不可变的 ,因此您不能就地修改它们。 You need to re-assign to the name to change its value - so here we assign a new number which is 1 greater than the last. 您需要重新分配名称以更改其值 -因此在这里我们分配一个比上一个大1的新数字。

Now it works with a demo: 现在可以使用演示了:

>>> list1 = [4, 7, 5, 3]
>>> list1[1] += 1
>>> print(list1)
[4, 8, 5, 3]

Only don't name a variable list , it masks the built-in. 仅不命名变量list ,它会掩盖内置变量。

>>> lst = [4, 7, 5, 3]
>>> lst[1]
7

To modify value of an item in a list, you assign new value to it by lst[i] = new_value 要修改列表中项目的值,请通过lst[i] = new_value为其分配新值

To increment existing value, you may calculate new value to assign: 要增加现有值,您可以计算新值以分配:

>>> lst[1] = lst[1] + 1
>>> lst[1]
8

There is also short notation for adding value to an existing value using += : 也有使用+=将值添加到现有值的简短符号:

>>> lst[1] += 1
>>> lst[1]
9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM