Search code examples
python-3.xlistlist-comprehension

How to convert this loop to nested list comprehension in Python


I have the following splitlist (it is just an excerpt):

 [['99', '1'],
 ['98s', '0.09434'],
 ['88', '1'],
 ['87s', '0.1014'],
 ['77', '1'],
 ['76s', '0.3212'],
 ['66', '1'],
 ['65s', '0.3335'],
 ['55', '0.6182'],
 ['54s', '0.3451'],
 ['44', '0.5147'],
 ['33', '0.4251'],
 ['22', '0.3753']]

I want to have the same list but to convert every 2nd string element to number.

So I wrote this loop:

convertedsplitlist = []

for x in splitlist:
    hand, freq = x
    convertedsplitlist.append([hand, float(freq)])

And it works.

I just can't wrap my head around how to do it with nested list comprehension.


Solution

  • This wil probably do the trick (untested):

    convertedsplitlist = [[a,float(b)] for a,b in splitlist]