【问题标题】:Adding multiple variables to lists within a list in Python将多个变量添加到 Python 列表中的列表
【发布时间】:2016-06-14 14:41:02
【问题描述】:

我想问一下如何将多个变量添加到 python 列表中的列表中。

yearmonthlst = [[] for i in range(64)]
precipitation = [197.6, 95.0, 37.1, 74.2, 65.3, 175.5, 114.6, 90.4, 26.7, 62.2, 58.9, 142.0, 129.0, 122.2...]

例如,这里我有一个列表,其中包含 64 个其他列表。然后我有另一个包含很多值的列表。对于降水中 13 日之前的每个值,它将在 yearmonthlst 内附加到列表中

[197.6, 95.0, 37.1, 74.2, 65.3, 175.5, 114.6, 90.4, 26.7, 62.2, 58.9, 142.0], ['''12 values within this list'''], ['''12 values within this list''']...]

我想在 yearmonthlst 内的每个列表中都有 12 个降水值。所以它从 precipitation[0] 到 [11] 将被附加到 yearmonthlst[0],然后迭代另一个列表 yearmonthlst[1],从在 precipitation 中迭代的值继续, 所以值 [12] - [23] 被附加到该列表中。

【问题讨论】:

    标签: python list loops iterator append


    【解决方案1】:
    [precipitation[i:i+12] for i  in range(0, len(precipitation), 12)]
    

    输入:

    precipitation = [197.6, 95.0, 37.1, 74.2, 65.3, 175.5, 114.6, 90.4, 26.7, 62.2, 58.9, 142.0, 129.0, 122.2]
    

    输出:

    [[197.6, 95.0, 37.1, 74.2, 65.3, 175.5, 114.6, 90.4, 26.7, 62.2, 58.9, 142.0], [129.0, 122.2]]
    

    【讨论】:

      【解决方案2】:

      这应该可行:

      for index, value in enumerate(precipitation):
          yearmonthlst[index % 12].append(value)
      

      【讨论】:

        猜你喜欢
        • 2021-09-11
        • 2013-01-29
        • 2022-11-16
        • 2014-07-25
        • 2020-09-10
        • 1970-01-01
        • 2023-03-31
        • 2020-11-05
        • 1970-01-01
        相关资源
        最近更新 更多