在二维蟒数组值分配给一个单独的细胞 [英] Assign value to an individual cell in a two dimensional python array

查看:97
本文介绍了在二维蟒数组值分配给一个单独的细胞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下空二维数组在Python:

  Q = [[无] * 5 * 4

我想在的第一列 5 的值赋给第一行。出于本能,我做到以下几点:

  Q [0] [0] = 5

不过,这会产生:

  [5,无,无,无,无]
  [5,无,无,无,无]
  [5,无,无,无,无]
  [5,无,无,无,无]

每一个的数组被初始化为 5 ,在这里我想到的只是第一个数组的第一个元素会得到更新的的第一个元素。我有两个问题:


  1. 为什么Python的初始化每个数组的第一个值,而不是只是第一个?

  2. 有没有更好的方式来完成我想要做什么?


解决方案

这不会做你希望的东西。

  Q = [[无] * 5 * 4

它重用列表对象多次。正如你所看到的,当你做了更改一个细胞,这是在重复使用列表对象。

一个单独的列表,值为 [无] 是使用5次。

一个单独的列表,值为 [无] * 5] 使用四次。

  Q = [无,我在范围内(5)]在范围[(4-)

可能会更你在找什么。

这明确地避免了重复使用一个列表对象。

的80%的时间,一本字典是你真正想要的东西。

  Q = {}
Q [0,0] = 5

也可以工作。你不值的pre-定义网格开始。但也很少需要他们摆在首位。

在Python 2.7和更高版本,可以做到这一点。

  Q = {(I,J):0我在范围内(5)范围内[(4-)}

这将建立由2元组索引的网格。

  {(0,1):0,(1,2):0,(3,2):0,(0,0):0,(3,3) :0,(3,0):0,(3,1):0,(2,1):0,(0,2):0,(2,0):0,(1,3):0 ,(2,3):0,(4,3):0,(2,2):0,(1,0):0,(4,2):0,(0,3):0,( 4,1):0,(1,1):0,(4,0):0}

Let's say I have the following empty two dimensional array in Python:

q = [[None]*5]*4

I want to assign a value of 5 to the first row in the first column of q. Instinctively, I do the following:

q[0][0] = 5

However, this produces:

 [[5, None, None, None, None], 
  [5, None, None, None, None], 
  [5, None, None, None, None], 
  [5, None, None, None, None]]

The first element of every array is being initialized to 5, where I thought only the first element of the first array would get the update. I have two questions:

  1. Why is Python initializing the first value of every array and not just the first one?
  2. Is there a better way to accomplish what I'm trying to do?

解决方案

This doesn't do what you hoped.

q = [[None]*5]*4

It reuses list objects multiple times. As you can see when you made a change to one cell, which was in a reused list object.

A single list with a value of [None] is used five times.

A single list with a value of [[None]*5] is used four times.

q = [ [ None for i in range(5) ] for j in range(4) ]

Might be more what you're looking for.

This explicitly avoids reusing a list object.

80% of the time, a dictionary is what you really wanted.

q = {}
q[0,0]= 5

Will also work. You don't start with a pre-defined grid of None values. But it's rare to need them in the first place.

In Python 2.7 and higher, you can do this.

q = { (i,j):0 for i in range(5) for j in range(4) }

That will build a grid indexed by 2-tuples.

{(0, 1): 0, (1, 2): 0, (3, 2): 0, (0, 0): 0, (3, 3): 0, (3, 0): 0, (3, 1): 0, (2, 1): 0, (0, 2): 0, (2, 0): 0, (1, 3): 0, (2, 3): 0, (4, 3): 0, (2, 2): 0, (1, 0): 0, (4, 2): 0, (0, 3): 0, (4, 1): 0, (1, 1): 0, (4, 0): 0}

这篇关于在二维蟒数组值分配给一个单独的细胞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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