更新时间:2023-01-15 16:08:00
O(1)
.或更准确地说,它等于按照您传递的任何序列查找单个索引的big-O随机访问时间,而list
具有O(1)
随机访问索引(就像tuple
). 简化了,它所做的只是seq[random.randrange(len(seq))]
,它显然等效于单个索引查找操作.
O(1)
. Or to be more precise, it's equivalent to the big-O random access time for looking up a single index in whatever sequence you pass it, and list
has O(1)
random access indexing (as does tuple
). Simplified, all it does is seq[random.randrange(len(seq))]
, which is obviously equivalent to a single index lookup operation.
将其作为O(n)
的示例是collections.deque
,其中deque
中间的索引是O(n)
(尽管具有较大的常数除数,所以除非deque
是达到数千个元素范围或更高).因此,基本上,不要使用deque
,如果它会变大并且打算重复从中选择随机元素,请坚持使用list
,tuple
,str
,byte
/bytearray
, array.array
和其他具有O(1)
索引的序列类型.
An example where it would be O(n)
is collections.deque
, where indexing in the middle of the deque
is O(n)
(with a largish constant divisor though, so it's not that expensive unless the deque
is reaching the thousands of elements range or higher). So basically, don't use a deque
if it's going to be large and you plan to select random elements from it repeatedly, stick to list
, tuple
, str
, byte
/bytearray
, array.array
and other sequence types with O(1)
indexing.