Python for 循环不断访问嵌套列表中的第一个元素
我有一个不同值的嵌套列表(在下面的代码片段中列出x
)。我还有一个 for 循环,它迭代列表中的每个索引,打印 0 到 2 之间的索引。
当我有相同值的嵌套列表时(列表 y )和下面代码片段中的 z
)循环打印 0
三次。
x = [[1,2,3],[4,5,6],[7,8,9]]
y = [['X' for x in range(3)] for x in range(3)]
z = [['X', 'X' 'X'], ['X', 'X' 'X'], ['X', 'X' 'X']]
for i in x:
print(x.index(i))
for i in y:
print(y.index(i))
for i in z:
print(z.index(i))
为什么第一个循环产生 0、1 和 2,而第二个/第三个循环只产生零?感谢您的帮助。
I have a nested list of different values (list x
in the below code snippet). I also have a for
loop that iterates over every index in the list, printing the indices between 0 and 2.
When I have a nested list of the same values (lists y
and z
in the below code snippet) the loop prints 0
three times.
x = [[1,2,3],[4,5,6],[7,8,9]]
y = [['X' for x in range(3)] for x in range(3)]
z = [['X', 'X' 'X'], ['X', 'X' 'X'], ['X', 'X' 'X']]
for i in x:
print(x.index(i))
for i in y:
print(y.index(i))
for i in z:
print(z.index(i))
Why does the first loop produce 0, 1, and 2 and the second/third loop produce only zeroes? Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.index()
返回您传入的参数的第一个实例的索引。对于第一个
for
循环,由于所有元素都是唯一的,.index()
返回其参数的唯一索引。在第二个中,所有元素都相同,因此返回第一个元素。.index()
returns the index of the first instance of the argument that you pass in.For the first
for
loop, since all the elements are unique,.index()
returns the only index of its argument. In the second, all the elements are the same, so the first element is returned.问题是函数 x.index(i) 找到第一个索引等于您描述的值。 Python 无法看到你已经得到了索引 0,所以在第二个 for 循环将 i 放入 y 后,它会获取索引 0 并且将始终采用该值,因为 i 的值始终等于 i = ['X', 'X' , 'X'] 是 x[0] = ['X', 'X', 'X'] 并且 x[0] 是等于 i 的第一个索引。
The problem is that function x.index(i) finds the first index which is equal to the value you described. Python cannot see that you have already got index 0, so after second for loop threw i in y it takes index 0 and will always take that value because the value of i which is always equal to i = ['X', 'X', 'X'] is x[0] = ['X', 'X', 'X'] and x[0] is the first index equal to i.