简体   繁体   中英

How to convert this loop to nested list comprehension in Pyhton

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.

这可能会奏效(未经测试):

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

one-liner using list-comprehension :

print([[x[0], float(x[1])] for x in splitlist])

OUTPUT:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM