【发布时间】:2016-11-14 06:35:27
【问题描述】:
所以我陷入了我不明白的事情。给定:
table # Type: tuple(tuple(str)).
data # Type: list(list(str)). Both ordered by rows.
当运行以下两个比较输出不同时,我想知道第一个输出的原因:
table == tuple(tuple(x for x in row) for row in data) -> False
all(table[i] == tuple(data[i]) for i in xrange(len(table))) -> True
== 如何处理嵌套序列和非嵌套序列?
进行比较的数据:
data = [['A1', 'B1', 'C1', 'D1'], ['A2', 'B2', 'C2', 'D2'], ['A3', 'B3', 'C3', 'D3'], ['A4', 'B4', 'C4', 'D4'], ['1', '2', '3', '4'], ['11', '2', '3', '1'], ['1.1', '2.2', '3.3', '4.0'], ['11', '2', '3', '1'], ['Area', '', 'None', 'Area Error']]
table = (('A1', 'B1', 'C1', 'D1'), ('A2', 'B2', 'C2', 'D2'), ('A3', 'B3', 'C3', 'D3'), ('A4', 'B4', 'C4', 'D4'), ('1', '2', '3', '4'), ('11', '2', '3', '1'), ('1.1', '2.2', '3.3', '4.0'), ('11', '2', '3', '1'), ('Area', '', 'None', 'Area Error'))
解决方案
对不起,我在交互式提示中检查后发现了它。 table 是另一个名为 rows 的对象的属性。我犯的错误是我太习惯于在出现索引和迭代器的地方传递rows(它们返回rows.table 元素),我忘记了它与table 的结构不同。实际错误:
rows == tuple(tuple(x for x in row) for row in data) # Should be `rows.table`.
对不起,一团糟。 但是比较问题仍然存在。
【问题讨论】:
-
能否给表格和数据的样本数据
-
向我们展示我们可以实际运行的代码,它实际演示了运行时的问题。您发布的
all版本应该给出TypeError,特别是TypeError: 'bool' object is not iterable。 -
我怀疑
data实际上比table长。table甚至可能是空的。 -
现在你已经修正了错字,我得到
True用于 Python 2.6 上的两个测试,data和table。顺便说一句,tuple(row)返回与tuple(x for x in row)相同的内容,只是它更短且更高效。 -
@PM2Ring 你说得对,谢谢。
标签: python python-2.7 nested comparison tuples