如何测试范围的等价性
我的一个单元测试在读取日志文件后检查范围是否设置正确,我只想测试 var == range(0,10)
。但是,在 Python 3 中,range(0,1) == range(0,1)
的计算结果为 False
。
是否有一种简单的方法来测试 Python 中范围的等价性3?
One of my unittests checks to see if a range is set up correctly after reading a log file, and I'd like to just test var == range(0,10)
. However, range(0,1) == range(0,1)
evaluates to False
in Python 3.
Is there a straightforward way to test the equivalence of ranges in Python 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在Python3中,
range
返回一个range
类型的可迭代对象。两个range
相等当且仅当它们相同(即共享相同的id
)。要测试其内容的相等性,请转换range
> 到列表
:这对于短距离来说效果很好。对于很长的范围,Charles G Waldman 的解决方案更好。
In Python3,
range
returns an iterable of typerange
. Tworange
s are equal if and only if they are identical (i.e. share the sameid
.) To test equality of its contents, convert therange
to alist
:This works fine for short ranges. For very long ranges, Charles G Waldman's solution is better.
第一个提出的解决方案 - 使用“列表”将范围转换为列表 - 效率低下,因为它首先将范围对象转换为列表(如果范围很大,可能会消耗大量内存),然后比较每个元素。考虑例如 a = range(1000000),
“范围”对象本身很小,但如果你将它强制到一个列表,它就会变得很大。然后你必须比较一百万个元素。
答案(2)的效率甚至更低,因为在进行元素比较之前,assertItemsEqual不仅会实例化列表,还会对它们进行排序。
相反,由于您知道对象是范围,因此当它们的步长、起始值和结束值相等时,它们相等。例如
ranges_equal = len(a)==len(b) and (len(a)==0 or a[0]==b[0] and a[-1]==b[-1])
The first proposed solution - use "list" to turn the ranges into lists - is ineffecient, since it will first turn the range objects into lists (potentially consuming a lot of memory, if the ranges are large), then compare each element. Consider e.g. a = range(1000000),
the "range" object itself is tiny but if you coerce it to a list it becomes huge. Then you have to compare one million elements.
Answer (2) is even less efficient, since the assertItemsEqual is not only going to instantiate the lists, it is going to sort them as well, before doing the elementwise comparison.
Instead, since you know the objects are ranges, they are equal when their strides, start and end values are equal. E.g.
ranges_equal = len(a)==len(b) and (len(a)==0 or a[0]==b[0] and a[-1]==b[-1])
尝试
assertItemsEqual
,(在 文档):Try
assertItemsEqual
, (in the docs):另一种方法是:
ranges_equal = str(a)==str(b) 字符串
表示形式指示范围的开始、结束和步长。
这个问题让我觉得也许Python应该提供一种从范围对象本身获取这些属性的方法!
Another way to do it:
ranges_equal = str(a)==str(b)
The string representation indicates the start, end and step of ranges.
This question makes me think that perhaps Python should provide a way to get these attributes from the range object itself!
抱歉死尸帖。但这是简单的方法。
Python 实现了一种测试范围是否相等的方法:
返回 True,因为范围具有相同的元素 (1, 101, ... , 901)
Sorry for the necropost. But here's the simple way.
Python implements a way to test if ranges are equal:
returns
True
as the ranges have the same elements (1, 101, ... , 901)