gpt4 book ai didi

python - 如何将 IP 地址转换为可用作字典键的 32 位地址

转载 作者:太空宇宙 更新时间:2023-11-03 11:23:27 24 4
gpt4 key购买 nike

如果我有一个 IP 地址,我可以将它用作字典中的键,如下所示:

dict = {}
IP = "172.23.1.99"
dict[IP] = "pear"

但是,如果我有很多,这会非常低效。

How can I convert the IP to a 32 bit representation which I can still use a key in a dict?

我可以将 IP 转换为 int。但是 python 整数似乎每个消耗 24 个字节,即 192 位,所以这没有解决我的问题。

In [2]: sys.getsizeof(2**32-1)
Out[2]: 24

因为我有上亿个这样的 IP,所以我真的很想将它们分别表示为 32 位。

从评论来看,这在纯 Python 中似乎很难。我也会很高兴有一个实用的非纯解决方案(包括使用 numpy 或任何其他容易获得的包)。

最佳答案

考虑到您打算存储的条目数,我建议您使用 SQLite。这既简单又可能足够有效。事实上,它有一个很好的特性,即对于每条记录,它只使用必要的空间。对于 1 到 5 个字节之间的 IP 地址,具体取决于 IP 地址(因此平均为 3 个字节)。

这是一个例子:

from ipaddress import ip_address
import sqlite3

# Create an in-memory database.*
db_connection = sqlite3.connect(':memory:')
cursor = db_connection.cursor()
cursor.execute('''
CREATE TABLE ip_address_associations (
ip_address INTEGER PRIMARY KEY,
value TEXT
)
''')

# Store the value for an IP address
cursor.execute(
'INSERT OR REPLACE INTO ip_address_associations VALUES (?, ?)',
(int(ip_address('172.23.1.99')), 'pear')
)

# Retrieve the value for an IP address
row = cursor.execute(
'SELECT value FROM ip_address_associations WHERE ip_address = ?',
(int(ip_address('172.23.1.99')),)
).fetchone()
if row:
value = row[0]
print(value)
else:
print('No results found.')

*虽然我不确切知道你的应用程序是关于什么的,但我高度怀疑没有必要一直将整个数据库保存在内存中。通过使用(临时)文件并依赖文件缓存,您可以大大节省内存使用量,同时不会损失太多访问时间。对于临时文件,将 ':memory:' 替换为 '',对于持久文件,替换为文件名。

关于python - 如何将 IP 地址转换为可用作字典键的 32 位地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38545718/

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