我有三个列表,其中有一些重复的值。我将它们用作x和y坐标。因此,我的第三个列表对应于要绘制为热图的值。 现在,我只能为一个列表分配z的值,如何使for循环对其余网格执行相同的操作?
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [5.9617e-09,6.3562e-09,6.819e-09,7.3562e-09,7.989e-09,8.6735e-
09,9.3898e-09,1.0139e-08,1.0912e-08,1.0912e-08]
xs = len(set(x))
ys = len(set(y))
grid = []
counter = 0
for row in range(ys):
rows = [] # creating the rows on the grid
if len(rows) < ys: # I want to loop over ys and assign the values os z to each coordinate
grid.append(z[counter])
counter = counter+1
print(grid)
一旦我有了一个二维数组,那么我就可以使用热图很好地绘制它了。
答案 0 :(得分:0)
最简单的方法是使用numpy
:
In [1]: z = [5.9617e-09,6.3562e-09,6.819e-09,7.3562e-09,
7.989e-09,8.6735e-09,9.3898e-09,1.0139e-08,
1.0912e-08,1.0912e-08]
In [2]: len(z)
Out[2]: 10
In [3]: import numpy as np
十个数字不适合3x3网格,因此跳过最后一个。
In [4]: nz = np.array(z[:-1])
Out[4]:
array([5.9617e-09, 6.3562e-09, 6.8190e-09, 7.3562e-09, 7.9890e-09,
8.6735e-09, 9.3898e-09, 1.0139e-08, 1.0912e-08])
In [5]: nz.reshape((3,3))
Out[5]:
array([[5.9617e-09, 6.3562e-09, 6.8190e-09],
[7.3562e-09, 7.9890e-09, 8.6735e-09],
[9.3898e-09, 1.0139e-08, 1.0912e-08]])
使用itertools
和functools
的普通Python解决方案:
In [6]: import itertools as it
...: import functools as ft
In [7]: def chunked(iterable, n): # {{{1
...: def take(n, iterable):
...: return list(it.islice(iterable, n))
...: return iter(ft.partial(take, n, iter(iterable)), [])
...:
In [8]: list(chunked(z[:-1], 3))
Out[8]:
[[5.9617e-09, 6.3562e-09, 6.819e-09],
[7.3562e-09, 7.989e-09, 8.6735e-09],
[9.3898e-09, 1.0139e-08, 1.0912e-08]]