gpt4 book ai didi

python - Python 中的元组数组

转载 作者:太空宇宙 更新时间:2023-11-04 07:37:00 24 4
gpt4 key购买 nike

这让我抓狂。下面的代码基本上就是问题所在。第一部分几乎立即停止。第二个似乎卡住了。但是,他们应该做完全相同的事情,因为 one == two

one = [[(0,)]] + [[], [], [], [], [], [], [], [], []]
n = 9
two = [[(0,)]] + ([[]] * n)

if (one == two):
print "It is indeed the same thing!"

print "Fast:"
strings = one
print str(strings)
for j in range(0, n):
for i in strings[j]:
strings[j + 1].append(i + (0,))
strings[j + 1].append(i + (1,))

print "Slow:"
strings = two
print str(strings)
for j in range(0, n):
for i in strings[j]:
strings[j + 1].append(i + (0,))
strings[j + 1].append(i + (1,))

最佳答案

Equals == 测试数组“看起来”是否相同(使用标准的相等性测试)。

但是它们不包含相同的对象!即对象引用不相同。

is 测试数组是否实际上相同。

[[],[],[]] 有三个不同的列表。

[[]]*3 具有对相同 列表的三个引用。

因此在 one 中,对于每个 j,您都将添加到不同的子列表中。但是在 two 中,您一直在向同一个子列表添加内容。


注意:使用 == 进行测试:equals 是一个属于列表的方法,可以重写以按照您想要的方式进行比较。它通常做“明智的事情”,在这种情况下,涉及查看列表的长度是否相同,如果是,则每个元素是否相同——使用 == 还有。但另一方面,is 是一种更原始​​的东西:它从字面上看你是否真的指的是同一个内存对象


要创建多个新的(不同的)对象,您可以这样做

[ [] for i in range(9) ]

关于python - Python 中的元组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32408431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com