dav*_*ave 4 python memory optimization out-of-memory
我正在尝试编译Apple设备将拥有的所有MAC地址的列表.oui.txt告诉我Apple已经分配了77个MAC范围.这些范围的形式为:
00:00:00
00:11:11
etc...
Run Code Online (Sandbox Code Playgroud)
这留给我追加的最后三个HEX数字.那是16^6.共有1291845632个Apple MAC地址.
我遇到的问题是编写一个程序来创建这些MAC地址的列表.这是我目前的代码:
import re
apple_mac_range = []
apple_macs = []
# Parse the HTML of http://standards.ieee.org/cgi-bin/ouisearch to get the MACs
with open('apple mac list', 'r') as f:
for line in f.readlines():
match = re.search(r'[\w\d]{2}-[\w\d]{2}-[\w\d]{2}', line)
if match:
apple_mac_range.append(match.group().split('-'))
for mac in apple_mac_range:
for i in range(1, 1291845633):
print i
Run Code Online (Sandbox Code Playgroud)
这给了我一个MemoryError......我怎样才能优化它?
Gab*_*abe 18
range(1, 1291845633)一次创建1,291,845,632个元素(几GB)的列表.使用xrange(1, 1291845633),而不是和你需要他们,而不是所有的一次就会产生元素.
无论如何,看起来你想要更像这样的东西:
for mac in apple_mac_range:
for i in xrange(16777216):
print mac, i
Run Code Online (Sandbox Code Playgroud)
当然,1.3e + 9 MAC地址列表很可能不会非常有用.如果您想查看给定的MAC地址是否为Apple设备,您应该检查3字节前缀是否在77的列表中.如果您尝试通过提供路由器或其他东西来进行访问控制所有可能的MAC地址列表,设备不太可能接受其列表中的1.3e + 9项.