gpt4 book ai didi

python - 迭代二维列表并从Python中的坐标中选择范围

转载 作者:行者123 更新时间:2023-11-30 23:03:22 24 4
gpt4 key购买 nike

gridsize=5

m= [[0 for i in range(gridsize)] for i in range(gridsize)]

[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]

在给定坐标范围的情况下,如何迭代 2D 列表并更改它们的值?

示例:坐标从 (0,0) 到 (0,3)

enter image description here

在这种情况下:需要更改m[0][0]、m[0][1]、m[0][2]和m[0][3]

示例 2:坐标 (2,2) 到 (2,4)

enter image description here

在本例中:m[2][2]、m[2][3] 和 m[2][4] 需要更改。

最佳答案

就像其他人所说的那样,这只是一个列表的列表

所以你可以用m[i][j]来索引它

但是您想要内部列表上的一个范围,因此您可以使用 m[i][j:k]

对其进行切片
>>> m = [[1, 2, 3, 4, 5],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0]]
>>> m[0]
[1, 2, 3, 4, 5]
>>> m[0][0:4]
[1, 2, 3, 4]

要改变你的列表,只需执行

>>> m[0][0:4] = ['a', 'b', 'c', 'd']
>>> m
[['a', 'b', 'c', 'd', 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

你的第二个例子

In this instance: m[2][2], m[2][3] and m[2][4] need to be changed.

这与上面的第一个示例不同,因为它跨越单行

m[2][2:5] = [1,1,1]

要进行更高级的矩阵/数组操作,请尝试 numpy

如果范围跨越超过 1 行,我建议您使用 numpy 库,因为它很容易展平

>>> m = np.zeros(shape=(5,5))
>>> m
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> f = m.flatten()
>>> f
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> f[4:7]
array([ 0., 0., 0.])
>>> f[4:7] = [1, 1, 1]
>>> f
array([ 0., 0., 0., 0., 1., 1., 1., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> f.shape = 5,5
>>> f
array([[ 0., 0., 0., 0., 1.],
[ 1., 1., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])

关于python - 迭代二维列表并从Python中的坐标中选择范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34126395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com