简体   繁体   English

2D数组的Python列表拼接

[英]Python list splicing for 2D array

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
matrix[3][1:] = matrix[3][0:-1]
print(matrix)

gives the following output: 给出以下输出:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 13, 14, 15]]

But: 但:

rows = 3
k = 0
matrix[rows-k][1+k:-k] = matrix[rows-k][k:-1-k]
print(matrix)

gives the following output: 给出以下输出:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 13, 14, 15, 14, 15, 16]]

Can someone please explain to me what's going on? 有人可以告诉我发生了什么吗?

Interesting question. 有趣的问题。

This happens because 这是因为

matrix[rows-k][1+k:-k] = matrix[rows-k][k:-1-k]

is equivalent to 相当于

matrix[3][1:0] = matrix[3][0:-1]

which is equivalent to 相当于

matrix[3][1:1] = matrix[3][0:-1]

So when you do matrix[3][1:0] => matrix[index][start:stop:None] 因此,当您执行matrix[3][1:0] => matrix[index][start:stop:None]

Your start value is 1, which is more than your stop value of 0. In case of start >= stop Python sets stop = start and returns an empty slice. 您的起始值为1,大于您的终止值0。如果start> = stop,则Python设置stop = start并返回一个空切片。

You can check the value of matrix[3][1:1] which is an empty slice like matrix[3][1:0] 您可以检查matrix [3] [1:1]的值,它是一个像矩阵[3] [1:0]一样的空切片

>>> matrix[3][1:0]
[]
>>> matrix[3][1:1]
[]

Read more: Python doc 阅读更多:Python 文档

If i is greater than or equal to j, the slice is empty 如果i大于或等于j,则切片为空

If you insert rows = 3 and k = 0: 如果您插入的行= 3且k = 0:

matrix[3][1:0] = matrix[3][0:-1]

And it is not the same like your second line: 您的第二行不同:

matrix[3][1:] = matrix[3][0:-1]

Added. 添加。

In first example you insert some data from 1. position to the end : 在第一个示例中,从1. position到end插入一些数据:

a = [1, 2, 3, 4]
a[1:] = [100, 200, 300]
print(a)
OUTPUT: [1, 100, 200, 300]

In the second case you insert a value between the 0. and 1. position : 在第二种情况下,您可以在0和1之间插入一个值

a = [1, 2, 3, 4]
a[1:0] = [100, 200, 300]
print(a)
OUTPUT: [1,100, 200, 300, 2, 3, 4]

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

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