python中如何访问列表元素,Python列表列表 - 访问单个元素

I am trying to access a particular element of a list of lists in Python. I am bringing a bit of C/Java baggage and thinking of this data structure as a 2D array. In my mind, the operation below should affect the first item of the first list only, loc1[0][0] in Java speak. In practice, the first item of each sublist is affected, i.e. loc1[0][0], loc1[1][0] and loc1[2][0]. Any idea why that is?

def move(loc, dir, nrows, ncols):

loc1 = [[0.0] * ncols] * nrows

for col in range(1):

for row in range(1):

loc1[row][col] += 100.0 * loc[row][col]

return loc1

nrows = 4

ncols = 3

p = [[1.0 / (ncols * nrows)] * ncols] * nrows #uniform prior

print p

p = move(p, [0, 1], nrows, ncols)

print p

解决方案

I've had this happen before and it's frustrating.

Your problem is this line of code, which isn't doing what you think it is:

loc1 = [[0.0] * ncols] * nrows

[0.0] * ncols creates a single list which is passed by reference to form your 2D list.

Try this:

loc1 = [[0.0 for y in range(ncols)] for x in range(nrows)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值