python列表生成式是一种基于其他iterable(如集合、元组、其他列表等)创建列表的方法。这种方法将整个输出列表加载到内存中,对于中小型的列表,这个是可取的,它可以使操作更快。大型的列表就不合适,不可取的,由于内存需求过大可能导致计算机崩溃。
下面介绍一下列表生成式:
import time
new_squares = [value**2 for value in range(1,51)]
print(new_squares)
print(time.thread_time())
输出结果为:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500]
0.8125
普通的迭代:
import time
squares = []
for value in range(1,51):
squares.append(value**2)
print(squares)
print(time.thread_time())
输出结果为:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500]
0.84375
紧接着我们来测试两个代码运行时占用的内存大小,我们引入一个psutil包,进行测试
"""set_out_list,py"""
import os
import psutil
def count_info(count):
def float_info():
pid = os.getpid()
p = psutil.Process(pid)
info_start = p.memory_full_info().uss/1024
count()
info_end = p.memory_full_info().uss/1024
print("占用"+str(info_end-info_start)+"kb")
return float_info
@count_info
def main():
squares = []
for value in range(1,51):
if value%2 == 0:
squares.append(value**2)
print(squares)
if __name__ == '__main__':
main()
"""set_out_list_new.py"""
import os
import psutil
def count_info(count):
def float_info():
pid = os.getpid()
p = psutil.Process(pid)
info_start = p.memory_full_info().uss/1024
count()
info_end = p.memory_full_info().uss/1024
print("占用"+str(info_end-info_start)+"kb")
return float_info
@count_info
def main():
new_squares = [value**2 for value in range(1,51) if value%2==0]
print(new_squares)
if __name__ == '__main__':
main()
运行结果图:
PS E:\pycharm\PyCharm 2021.3\pythonproject> python .\set_out_list.py
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304, 2500]
占用4.0kb
PS E:\pycharm\PyCharm 2021.3\pythonproject> python .\set_out_list_new.py
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304, 2500]
占用4.0kb
我们发现内存占用一样都是4.0kb。