【问题标题】:Adding a value to a list of lists将值添加到列表列表
【发布时间】:2015-11-28 02:13:23
【问题描述】:

我想向列表列表中添加一个值。
对于 [[1,2],[2,3]] 的输入 我想要 [[2,3],[3,4]] 的输出 我可以用循环来做到这一点:

list_of_lists = [[1,2],[2,3]]
output = []
for list in list_of_lists:
    sub_output = []
    for value in list:
        sub_output.append(value+1)
    output.append(sub_output)
print(output)

我可以通过列表理解来做到这一点吗?

如果我这样做:

[value + 1 for list in list_of_lists for value in list]

它给了我 [2,3,3,4]。我可以让它以某种方式保持子列表格式吗?

【问题讨论】:

    标签: python list-comprehension


    【解决方案1】:

    试试……

    [ [n + 1 for n in inner_list] for inner_list in list ]
    

    【讨论】:

      【解决方案2】:

      是的,你需要一个嵌套理解:

      [[item + 1 for item in list] for list in list_of_lists]
      

      另一种方法是使用map:

       map(lambda l: map(lambda i: i + 1, l), list_of_lists)
      

      【讨论】:

        【解决方案3】:

        您需要在该理解中嵌套一个理解。解压缩每个子列表以使其更容易。

        [[a+1, b+1] for a,b in list_of_lists]
        

        【讨论】:

          猜你喜欢
          • 2021-09-25
          • 2021-12-13
          • 1970-01-01
          • 2011-10-23
          • 2017-11-10
          • 1970-01-01
          • 1970-01-01
          • 2021-01-23
          • 2012-02-13
          相关资源
          最近更新 更多