gpt4 book ai didi

Python 集合与数组

转载 作者:太空狗 更新时间:2023-10-29 19:26:25 26 4
gpt4 key购买 nike

我需要在内存中存储大量数字。然后我需要检查成员(member)资格。在内存效率方面,数组优于列表。对于成员检查,集合优于列表。我两个都需要!所以我的问题是:

1) 数组比集合的内存效率高多少? (相反,请参阅下面的结果)。2)是否有一种数据结构可以在集合和数组之间取得更好的平衡?类似于带符号整数类型的集合?或者一些 numpy 结构?

我用下面的脚本检查了成员资格时间差异。 (我知道 timeit 更好,但方差足够低,时间就可以了):

import array
import time

class TimerContext:
def __enter__(self):
self.t0 = time.time()
def __exit__(self, *args, **kwargs):
print(time.time()-self.t0)

SIZE = 1000000

l = list([i for i in range(SIZE)])
a = array.array('I', l)
s = set(l)

print(type(l))
print(type(a))
print(type(s))

with TimerContext():
x = 99999 in l
with TimerContext():
x = 99999 in a
with TimerContext():
x = 99999 in s

结果:

<class 'list'>
<class 'array.array'>
<class 'set'>
0.0012176036834716797
0.0024595260620117188
1.430511474609375e-06

所以集合对于成员检查来说要快很多(请注意科学记数法)。因此,如果它们的内存占用量与数组没有太大区别,我会更喜欢使用集合。但是我不知道如何检查内存占用。

我还应该补充一点,比较集合和列表的问题很多。但是我没有看到比较数组和集合的任何好的答案。

最佳答案

如果您的情况可行,bisect性能接近 set 用于成员检查(列表和数组)。查看下面的结果

import array
from bisect import bisect
import sys
import time


class TimerContext:
def __enter__(self):
self.t0 = time.time()

def __exit__(self, *args, **kwargs):
print(time.time() - self.t0)


def get_size_in_megabytes(iterable):
return round(sys.getsizeof(iterable) / (1024 ** 2), 2)


SIZE = 1000000

l = list([i for i in range(SIZE)])
a = array.array("I", l)
s = set(l)

print(type(l), get_size_in_megabytes(l))
print(type(a), get_size_in_megabytes(a))
print(type(s), get_size_in_megabytes(s))

with TimerContext():
x = 99999 in l
with TimerContext():
x = 99999 in a
with TimerContext():
x = 99999 in s

print("list bisect")
with TimerContext():
bisect(l, 99999)

print("array bisect")
with TimerContext():
bisect(a, 99999)

结果:

<class 'list'> 8.58
<class 'array.array'> 3.81
<class 'set'> 32.0
0.0024390220642089844
0.0053005218505859375
3.814697265625e-06
list bisect
9.298324584960938e-06
array bisect
6.198883056640625e-06

感谢@CristiFati 对 sys.getsizeof 的使用。

关于Python 集合与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55766238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com