Python中的元组数组 [英] Array of tuples in Python

查看:58
本文介绍了Python中的元组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真让我发疯。以下代码基本上是问题。第一部分几乎立即停止。第二个似乎卡住了。但是,他们应该做完全相同的事情,因为 one == 2

This is driving me nuts. The following code is basically the question. The first part halts almost immediately. The second seems to get stuck. However, they should be doing the exact same thing, since 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 == tests whether the arrays "look" the same (using standard tests of equality).

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

However they don't contain the same objects! i.e. the object references are not the same.

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

is tests whether the arrays are actually the same.

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

[[],[],[]] has three different lists.

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

[[]]*3 has three references to the same list.

因此,在中,每个 j 都添加到另一个子列表中。但是在两个中,您一直都在添加到同一子列表中。

So in one, for each j you're adding to a different sub-list. But in two you are adding to the same sub-list all the time.

注意:使用 == 进行测试: equals 是属于列表的方法,可以被覆盖以您想要的方式进行比较。它通常执行明智的事情,在这种情况下,这涉及查看列表是否长度相同,如果长度相同,则每个元素是否相同-使用 == 。但是,另一方面,:它实际上是在查看您是否真的在指相同的内存对象

Note re: testing with ==: equals is a method belonging to the list, and can be overridden to compare in the way you want to. It usually does "the sensible thing", which in this case, involves seeing if the lists are the same length, and if so, whether each of the elements are the same -- using == also. But is, on the other hand, is a more primitive thing: it literally sees if you are really referring to the same memory object.

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

to create multiple new (different) objects, you could do

[ [] for i in range(9) ]

这篇关于Python中的元组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆