【问题标题】:How to convert this loop to nested list comprehension in Python如何在 Python 中将此循环转换为嵌套列表理解
【发布时间】:2020-12-31 06:11:24
【问题描述】:

我有以下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)])

而且它有效。

我只是想不通如何使用嵌套列表理解来做到这一点。

【问题讨论】:

  • 你的预期输出是什么?

标签: python-3.x list list-comprehension


【解决方案1】:

单行使用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]] 

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-02
      • 2017-11-23
      • 2022-10-07
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2021-02-03
      相关资源
      最近更新 更多