为什么x [i] [:] = x [:] [i]其中x是列表列表?

ipl*_*uto 7 python list

我正在处理列表列表和访问列非常混乱.

我们假设x定义如下:

  x = [[int(np.random.rand()*100) for i in xrange(5)] for x in xrange(10)]
  pprint.pprint(x)
Run Code Online (Sandbox Code Playgroud)
[[86, 92, 95, 78, 68],
 [76, 80, 44, 30, 73],
 [48, 85, 99, 35, 14],
 [3, 84, 50, 39, 47],
 [3, 7, 67, 28, 65],
 [19, 13, 98, 53, 33],
 [9, 97, 35, 25, 89],
 [48, 3, 48, 5, 1],
 [21, 40, 72, 61, 62],
 [58, 43, 84, 69, 26]]
Run Code Online (Sandbox Code Playgroud)

现在,双方x[1][:]x[:][1]产生相同的结果:

[76, 80, 44, 30, 73]
Run Code Online (Sandbox Code Playgroud)

有人可以解释原因吗?谢谢

Blc*_*ght 6

如果将每个表达式的两个索引操作分解为单独的部分,则行为很容易理解.

  • x[1]将是列表列表中的第二个值(列表[76, 80, 44, 30, 73]).
  • x[1][:]x[1](横跨整个列表的切片)的副本.
  • x[:]x(列表清单)的(浅)副本.
  • x[:][1]是复制的列表列表中的第二个值,与列表相同x[1].

所以,这两个表达方式是相同的.请注意,因为第一个表达式复制列表([:]末尾有切片),所以它们不是同一个对象(x[1][:] is x[:][1]将是False).

如果您使用的是2D numpy数组,则会得到不同的行为,因为您可以切换任意维度(使用稍微不同的语法):

import numpy as np

x = np.array([[86, 92, 95, 78, 68],
              [76, 80, 44, 30, 73],
              [48, 85, 99, 35, 14],
              [3, 84, 50, 39, 47],
              [3, 7, 67, 28, 65],
              [19, 13, 98, 53, 33],
              [9, 97, 35, 25, 89],
              [48, 3, 48, 5, 1],
              [21, 40, 72, 61, 62],
              [58, 43, 84, 69, 26]])

print(x[1,:]) # prints the values of the second row: [76 80 44 30 73]
print(x[:,1]) # prints the values of the second column: [92 80 85 84  7 13 97  3 40 43]
Run Code Online (Sandbox Code Playgroud)

这可能就是你要找的东西.