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

问题描述

因此,当某事物的长度接近1

So, cPython (2.4) has some interesting behaviour when the length of something gets near to 1<<32 (the size of an int).

r = xrange(1<<30)
assert len(r) == 1<<30

没问题,但是:

r = xrange(1<<32)
assert len(r) == 1<<32
ValueError: xrange object size cannot be reported`__len__() should return 0 <= outcome

Alex的也有这种行为。 wowrange(1<<< 32).l 没问题,但 len(wowrange(1<< 32))很糟糕。我猜这里有一些浮点行为(被视为负面)行动。

Alex's wowrange has this behaviour as well. wowrange(1<<32).l is fine, but len(wowrange(1<<32)) is bad. I'm guessing there is some floating point behaviour (being read as negative) action going on here.


  1. 这里究竟发生了什么? (这在下面已经很好地解决了!)

  2. 我该如何解决这个问题?多头?

  1. What exactly is happening here? (this is pretty well-solved below!)
  2. How can I get around it? Longs?

(我的具体应用是 random.sample(xrange(1<< 32),ABUNCH)) 如果有人想直接解决这个问题!)

(My specific application is random.sample(xrange(1<<32),ABUNCH)) if people want to tackle that question directly!)

推荐答案

cPython假设列表适合内存。这扩展到行为类似于列表的对象,例如xrange。实质上, len 函数需要 __ len __ 方法返回可转换为 size_t ,如果逻辑元素的数量太大,即使这些元素实际上不存在于内存中也不会发生。

cPython assumes that lists fit in memory. This extends to objects that behave like lists, such as xrange. essentially, the len function expects the __len__ method to return something that is convertable to size_t, which won't happen if the number of logical elements is too large, even if those elements don't actually exist in memory.

这篇关于Python,len和整数的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:23