简体   繁体   English

迭代2d列表并从Python中的坐标中选择范围

[英]Iterate through 2d list and select range from co-ordinates in Python

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]]

How could I iterate through the 2D list, given the range of co-ordinates and change their values? 在给定坐标范围并改变其值的情况下,我如何迭代2D列表?

Example: Co-ordinates from position (0,0) to (0,3) 示例:从位置(0,0)到(0,3)的坐标

在此输入图像描述

In this instance: m[0][0], m[0][1], m[0][2] and m[0][3] need to be changed. 在这种情况下:需要更改m[0][0], m[0][1], m[0][2] and m[0][3]

Example 2: Co-ordinates (2,2) to (2,4) 例2:坐标(2,2)到(2,4)

在此输入图像描述

In this instance: m[2][2], m[2][3] and m[2][4] need to be changed. 在这种情况下:需要更改m[2][2], m[2][3] and m[2][4]

Like others have said it's just a list of lists 像其他人一样说它只是一个列表清单

So you can index it with m[i][j] 所以你可以用m[i][j]索引它

But you want a range on the internal list, so you can slice it with m[i][j:k] 但是你想在内部列表上有一个范围,所以你可以用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]

To mutate your list, just do 要改变你的列表,就这样做

>>> 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]]

Your second example 你的第二个例子

In this instance: m[2][2], m[2][3] and m[2][4] need to be changed. 在这种情况下:需要更改m [2] [2],m [2] [3]和m [2] [4]。

This is on different than the first example above, because it spans a single row 这与上面的第一个示例不同,因为它跨越一行

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

For more advanced matrix/array manipulation try numpy 对于更高级的矩阵/数组操作尝试numpy

If the range spans more than 1 row, I suggest you use the numpy library, because it's got easy flattening 如果范围超过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.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM