1

So. I have a list containing lists

>>> 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']]

I want to change each value within each of the lists within the main list to an int. In other words, I want to end up with this

>>> 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]]

Now, I can easily do so with the following code:

for x in range(len(f)):
    for y in range(6):
        f[x][y] = int(f[x][y])

But I wanted to know if I could do this using list comprehension. I tried the following code

f = [int(x) for y in f for x in y]

but that results in one large list

>>> f[:10]
[-340, 495, -153, -910, 835, -947, -175, 41, -421, -714]

Anyone know how to accomplish the desired result using list comprehension?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Edward Garemo
  • 434
  • 3
  • 13

2 Answers2

2

With f as the starting list, use a nested comprehension:

>>> 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]]

Or list and 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]]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
2

You need a nested list comprehension for this. Try:

[[int(x) for y in f] for x in y]
Anomitra
  • 1,111
  • 15
  • 31