python二维列表添加元素_Python二维列表为元素添加值(Python two dimensional list add value to element)...

本文探讨了在Python中向二维列表的特定元素添加值时遇到的问题及其解决方案。通过示例代码展示了不当创建二维列表导致的错误,并给出了正确的创建和修改列表的方法。
摘要由CSDN通过智能技术生成

Python二维列表为元素添加值(Python two dimensional list add value to element)

我想为二维列表的元素添加一个值。 而是将值添加到列的所有元素中。 有人可以帮忙吗?

ROWS=3

COLUMNS=5

a=[[0] * (ROWS)] * (COLUMNS)

for i in range(ROWS):

print (a[i])

print("")

x=5

a[2][1]=a[2][1]+x

for i in range(ROWS):

print (a[i])

I want to add a value to an element of a two dimensional list. Instead the value is added to all the elements of the column. Could anyone help?

ROWS=3

COLUMNS=5

a=[[0] * (ROWS)] * (COLUMNS)

for i in range(ROWS):

print (a[i])

print("")

x=5

a[2][1]=a[2][1]+x

for i in range(ROWS):

print (a[i])

原文:https://stackoverflow.com/questions/12986983

2019-11-18 13:11

满意答案

像这样创建你的列表:

In [6]: a = [[0 for _ in range(rows)] for _ in range(cols)]

In [7]: a[2][1] = a[2][1] + 5

In [8]: a

Out[8]: [[0, 0, 0], [0, 0, 0], [0, 5, 0], [0, 0, 0], [0, 0, 0]]

因为你当前的方式,它实际上只是重复相同的列表对象,所以改变一个实际上改变它们中的每一个。

In [11]: a = [[0] * (rows)] * (cols)

In [12]: [id(x) for x in a]

Out[12]: [172862444, 172862444, 172862444, 172862444, 172862444] #same id(), i.e same object

Create you list like this:

In [6]: a = [[0 for _ in range(rows)] for _ in range(cols)]

In [7]: a[2][1] = a[2][1] + 5

In [8]: a

Out[8]: [[0, 0, 0], [0, 0, 0], [0, 5, 0], [0, 0, 0], [0, 0, 0]]

Because the way you are currently doing it, it actually just repeats the same list object, so changing one actually changes each of them.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值