我在数据结构和算法教科书中做了一些练习问题,以提高我的Python技能,并要求我重新设计这段代码:
import sys
data = []
for k in range(15):
a= len(data)
b=sys.getsizeof(data)
print('Length: {0:3d}; Size in bytes: {1:4d}'.format(a,b))
data.append(None)
输出:
Length: 0; Size in bytes: 64
Length: 1; Size in bytes: 96
Length: 2; Size in bytes: 96
Length: 3; Size in bytes: 96
Length: 4; Size in bytes: 96
Length: 5; Size in bytes: 128
Length: 6; Size in bytes: 128
Length: 7; Size in bytes: 128
Length: 8; Size in bytes: 128
Length: 9; Size in bytes: 192
Length: 10; Size in bytes: 192
Length: 11; Size in bytes: 192
Length: 12; Size in bytes: 192
Length: 13; Size in bytes: 192
Length: 14; Size in bytes: 192
所以我会找到"大小的最大长度,以字节为单位"。例如,192的最大长度为14,128的最大长度为8,等等。
我的第一个想法是遍历数据列表并在值更改为最大值之前设置数字。但我的Python很弱,我想知道如何解决这个问题。
非常感谢! 对不起,如果我犯了任何错误。我是网站的新手。
答案 0 :(得分:0)
您可以通过将数据存储在词典中并将itertools.groupby
与operator.itemgetter
结合使用来解决此问题。
import sys
import itertools as it, operator as op
data = []
for k in range(15):
d = {}
d['Length'] = len(data)
d['Size in bytes'] = sys.getsizeof(data)
data.append(d)
for k,g in it.groupby(data,key=op.itemgetter('Size in bytes')):
print(k,max(i['Length'] for i in g))
结果:
(72, 0)
(104, 4)
(136, 8)
(200, 14)