如何在 Python 中将此循环转换为嵌套列表理解
How to convert this loop to nested list comprehension in Python
我有以下splitlist
(只是摘录):
[['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']]
我想要相同的列表,但要将每个第二个字符串元素转换为数字。
所以我写了这个循环:
convertedsplitlist = []
for x in splitlist:
hand, freq = x
convertedsplitlist.append([hand, float(freq)])
而且有效。
我只是想不通如何使用嵌套列表理解来做到这一点。
这可能会成功(未经测试):
convertedsplitlist = [[a,float(b)] for a,b in splitlist]
one-liner 使用 list-comprehension
:
print([[x[0], float(x[1])] for x in splitlist])
输出:
[['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]]
我有以下splitlist
(只是摘录):
[['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']]
我想要相同的列表,但要将每个第二个字符串元素转换为数字。
所以我写了这个循环:
convertedsplitlist = []
for x in splitlist:
hand, freq = x
convertedsplitlist.append([hand, float(freq)])
而且有效。
我只是想不通如何使用嵌套列表理解来做到这一点。
这可能会成功(未经测试):
convertedsplitlist = [[a,float(b)] for a,b in splitlist]
one-liner 使用 list-comprehension
:
print([[x[0], float(x[1])] for x in splitlist])
输出:
[['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]]