因此。我有一个包含列表的列表
ShopCreatedEvent
我想将主列表中每个列表中的每个值更改为int。换句话说,我想最终得到这个
lastProcessed + 1 == currentVersion
现在,我可以使用以下代码轻松完成此操作:
>>> f[:10]
[['-340', '495', '-153', '-910', '835', '-947'], ['-175', '41', '-421', '-714', '574', '-645'], ['-547', '712', '-352', '579', '951', '-786'], ['419', '-864', '-83', '650', '-399', '171'], ['-429', '-89', '-357', '-930', '296', '-29'], ['-734', '-702', '823', '-745', '-684', '-62'], ['-971', '762', '925', '-776', '-663', '-157'], ['162', '570', '628', '485', '-807', '-896']]
但我想知道我是否可以使用列表理解来做到这一点。我尝试了以下代码
>>> f[:10]
[[-340, 495, -153, -910, 835, -947], [-175, 41, -421, -714, 574, -645], [-547, 712, -352, 579, 951, -786], [419, -864, -83, 650, -399, 171], [-429, -89, -357, -930, 296, -29], [-734, -702, 823, -745, -684, -62], [-971, 762, 925, -776, -663, -157], [162, 570, 628, 485, -807, -896]]
但这导致一个大的列表
for x in range(len(f)):
for y in range(6):
f[x][y] = int(f[x][y])
任何人都知道如何使用列表理解来完成所需的结果?
答案 0 :(得分:3)
你需要一个nested list comprehension。尝试:
[[int(x) for y in f] for x in y]
答案 1 :(得分:2)
以f
作为起始列表,使用嵌套理解:
>>> import pprint
>>> result = [[int(x) for x in l] for l in f]
>>> pprint.pprint(f)
[['-340', '495', '-153', '-910', '835', '-947'],
['-175', '41', '-421', '-714', '574', '-645'],
['-547', '712', '-352', '579', '951', '-786'],
['419', '-864', '-83', '650', '-399', '171'],
['-429', '-89', '-357', '-930', '296', '-29'],
['-734', '-702', '823', '-745', '-684', '-62'],
['-971', '762', '925', '-776', '-663', '-157'],
['162', '570', '628', '485', '-807', '-896']]
>>> pprint.pprint(result)
[[-340, 495, -153, -910, 835, -947],
[-175, 41, -421, -714, 574, -645],
[-547, 712, -352, 579, 951, -786],
[419, -864, -83, 650, -399, 171],
[-429, -89, -357, -930, 296, -29],
[-734, -702, 823, -745, -684, -62],
[-971, 762, 925, -776, -663, -157],
[162, 570, 628, 485, -807, -896]]
或list
和map
:
>>> result = [list(map(int, l)) for l in f]
>>> pprint.pprint(result)
[[-340, 495, -153, -910, 835, -947],
[-175, 41, -421, -714, 574, -645],
[-547, 712, -352, 579, 951, -786],
[419, -864, -83, 650, -399, 171],
[-429, -89, -357, -930, 296, -29],
[-734, -702, 823, -745, -684, -62],
[-971, 762, 925, -776, -663, -157],
[162, 570, 628, 485, -807, -896]]