Python 仅访问嵌套字典列表中的一个键并使用matplotlib打印它
我有一个嵌套的字典列表,创建方式如下:Python 仅访问嵌套字典列表中的一个键并使用matplotlib打印它,python,python-2.7,matplotlib,Python,Python 2.7,Matplotlib,我有一个嵌套的字典列表,创建方式如下: N = 30 grid = [] for row in range(N): rows = [] for column in range(N): each_cell = {"check": 0, "type": -1} rows.append(each_cell) grid.append(rows) import numpy.random as rnd import matplotlib.pyplot as plt
N = 30
grid = []
for row in range(N):
rows = []
for column in range(N):
each_cell = {"check": 0, "type": -1}
rows.append(each_cell)
grid.append(rows)
import numpy.random as rnd
import matplotlib.pyplot as plt
for i in range (rnd.randint(0, N*N)):
x = rnd.randint(0, N)
y = rnd.randint(0, N)
grid[x][y]['check'] = 1
if grid[x][y]['check'] == 1:
grid[x][y]['type'] = rnd.randint(0,4)
类型是我要绘制的类型,值-1表示单元格中没有任何内容,0,1,2,3是不同的类型(不是渐变),我希望用不同的颜色来表示
我将随机数目的类型放入网格,如下所示:
N = 30
grid = []
for row in range(N):
rows = []
for column in range(N):
each_cell = {"check": 0, "type": -1}
rows.append(each_cell)
grid.append(rows)
import numpy.random as rnd
import matplotlib.pyplot as plt
for i in range (rnd.randint(0, N*N)):
x = rnd.randint(0, N)
y = rnd.randint(0, N)
grid[x][y]['check'] = 1
if grid[x][y]['check'] == 1:
grid[x][y]['type'] = rnd.randint(0,4)
我试图用以下方法绘制它:
plt.imshow(grid['type'], interpolation = 'nearest', cmap = 'gist_ncar_r')
plt.show()
但是很明显,
网格['type']
并不是只挑选我想要的类型,有人知道如何解决这个问题吗?你可以使用列表理解将你想要的数据放入数组:
from numpy import *
...
data = array([[grid[i][j]['type'] for j in range(N)] for i in range(N)])
要使用array
您需要执行numpy
导入
然后你可以把它画出来,就像你试图:
matplotlib.pyplot.imshow(data, interpolation = 'nearest', cmap = 'gist_ncar_r')
matplotlib.pyplot.show()
由于
imshow
需要一个“类似数组”的文件,您可以更改数据的结构,使其更易于使用。不要使用dict数组,而是使用dict数组
import numpy.random as rnd
import matplotlib.pyplot as plt
N = 30
grid = {'check': [], 'type': []}
for row in range(N):
check_rows = []
type_rows = []
for column in range(N):
check_rows.append(0)
type_rows.append(1)
grid['check'].append(check_rows)
grid['type'].append(type_rows)
for i in range (rnd.randint(0, N*N)):
x = rnd.randint(0, N)
y = rnd.randint(0, N)
grid['check'][x][y] = 1
if grid['check'][x][y] == 1:
grid['type'][x][y] = rnd.randint(0,4)
plt.imshow(grid['type'], interpolation = 'nearest', cmap = 'gist_ncar_r')
plt.show()
第二个代码块是否要在第一个代码块之后运行?我得到
索引器:列表索引超出范围
。为避免索引器:列表索引超出范围
,在设置x
和y
@mfcovington是时,应使用rnd.randint(0,N-1)
,当我将它们一起运行时,我没有遇到错误。如何通过编写grid['check'][x][y]
和grid['type'][x][y]
来重新排列多数组网格的索引(从而最终它将成为一个dict)?实际上,您没有指定使用的是numpy.random
而不是内置的random
。它与numpy
版本一样工作,但不是内置的。这看起来像我需要的,但我得到了NameError:name'array'未定义
这似乎工作得非常好,非常感谢!这无疑使访问特定密钥变得更容易,这正是我想要的:)@Berci哈哈,对不起,我没有完全理解你的意思,我对编程非常陌生,所以我为之前没有理解你而道歉。