简体   繁体   English

这些列表有什么区别?

[英]What's the difference between these lists?

In my intro computer science class we just finished writing a program to create a tic tac toe board and the way I made my game board was like this;在我的计算机科学入门课上,我们刚刚编写了一个程序来创建一个井字游戏板,我制作游戏板的方式是这样的;

game_board = [[', ', '], [', ', '],[', ', ']]

I viewed similar problems on the internet and saw another way it was written like this我在互联网上查看了类似的问题,并看到了另一种写法

different_board = [[' '] * 3 for row in range(3)]

I was wondering how the second one would look compared to the first one if it were written out, would they be the same or would it look different?我想知道如果写出来,第二个与第一个相比会是什么样子,它们是相同的还是不同的?

You can just ask Python:你可以问问 Python:

a = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
b = [[' '] * 3 for row in range(3)]
print(a == b)

Result:结果:

True

Also, beware:另外,请注意:

c = c = [[' '] * 3] * 3
d = [[' ' for _ in range(3)] for _ in range(3)]
print(a == c)
print(a == d)

They appear the same, but they are only similar - try modifying c and you'll see why:它们看起来相同,但它们只是相似 - 尝试修改c ,你会明白为什么:

c[0][1] = 'x'
print(c)

Result:结果:

[[' ', 'x', ' '], [' ', 'x', ' '], [' ', 'x', ' ']]

It's three references to the same list!这是对同一个列表的三个引用! The definition of d is correct, but it's not immediately clear to most programmers why * 3 has that problem and for _ in range(3) would not, so I'd stay away from these "efficient" definitions. d的定义是正确的,但大多数程序员并不清楚为什么* 3有这个问题而for _ in range(3)不会,所以我会远离这些“有效”的定义。

And you could see what it looks like yourself:你可以看到自己的样子:

print(b)

Result:结果:

[[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]

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

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