【问题标题】:Python - stuck with correct list assignmentPython - 坚持正确的列表分配
【发布时间】:2021-08-23 03:38:33
【问题描述】:

事情是这样的:

coords = [['60', '01'], ['30', '19']]
coords = [int(coords[i][j])/60**j for i in range(2) for j in range(len(coords[i]))]

预期输出:

>>>[[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]

我有什么:

>>>[60.0, 0.016666666666666666, 30.0, 0.31666666666666665]

给我一​​个提示:如何通过列表推导以所需的方式分配值?

【问题讨论】:

标签: python list list-comprehension


【解决方案1】:

尝试切换for循环的顺序并添加括号:

coords = [[int(coords[i][j])/60**j for j in range(len(coords[i]))] for i in range(2)]
print(coords)

输出:

[[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]

【讨论】:

  • 多么巧合!
【解决方案2】:

由于您已将值 2 硬编码为内部数组的长度,因此您可以使用更简单的理解:

coords = [[int(a), int(b)/60] for a,b in coords ]

【讨论】:

  • 是的!事实上,将它们建模为元组可能更正确,因为它似乎是一个有序对。 data = [('60', '01'), ('30', '19')]; coords = [(int(a), int(b)/60) for a,b in coords]
  • @AdamSmith - 我同意。这些是列表的唯一原因是匹配 OP 请求的输出。
【解决方案3】:

您可以移动第二个 for 循环并将其括在括号中:

coords = [[int(coords[i][j])/60**j for j in range(len(coords[i]))] for i in range(2) ]

输出:

[[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]

【讨论】:

    【解决方案4】:
    [[int(j)/60**idx for idx, j in enumerate(i)] for i in coords]
    
    [[60.0, 0.016666666666666666], [30.0, 0.31666666666666665]]
    

    【讨论】:

      【解决方案5】:
      [
       [int(element)/60**i for i, element in enumerate(sublist)]
           for sublist in coords
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-13
        • 2014-10-18
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        • 2015-12-26
        相关资源
        最近更新 更多