【问题标题】:What is a proper way to re-order the values of a list inside a list?在列表中重新排序列表值的正确方法是什么?
【发布时间】:2021-12-07 23:22:06
【问题描述】:

我想对a_list 中的列表值重新排序。

这是我目前的 sn-p:

a_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
order = [1, 0, 2]

a_list = [a_list[i] for i in order] 

print(a_list)

这是我当前的输出:

[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

这是我想要的输出:

[['b', 'a', 'c'], ['b', 'a', 'c'], ['b', 'a', 'c']]

【问题讨论】:

    标签: python list reorderlist


    【解决方案1】:

    您需要访问a_list 的每个子列表,然后在该子列表中重新排序。使用列表理解,它会像:

    a_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
    order = [1, 0, 2]
    
    a_list = [[sublst[i] for i in order] for sublst in a_list]
    
    print(a_list) # [['b', 'a', 'c'], ['b', 'a', 'c'], ['b', 'a', 'c']]
    

    您当前的代码会自行重新排序子列表;即,例如,如果您从

    开始
    a_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
    

    那么结果应该是

    [['d', 'e', 'f'], ['a', 'b', 'c'], ['g', 'h', 'i']]
    

    【讨论】:

    • 很高兴它有帮助。在我看来,习惯嵌套列表推导是件好事。
    • @Andalusia,我同意 j1-lee 列表推导非常强大,并且在我看来更容易,一旦习惯了它们。
    • @j1-lee 现在如果a_list 中的列表长度不同怎么办?
    • @Andalusia 然后你需要为每个子列表指定一个顺序。 [1, 0, 2] 不会申请长度为 2 或 4 的子列表。在这种情况下,使用 zip 会起作用。或者,在 marmeladze 中定义一个函数可能更容易阅读,因为代码变得更长了。
    【解决方案2】:

    首先,您需要为a_list 中的子列表找到解决方案。因此,您将能够将该解决方案映射到 a_list 元素。

    def reorder(xs, order):
        # I am omitting exceptions etc. 
        return [xs[n] for n in order]
    
    

    然后您可以安全地将这个函数映射(理解)到列表列表。

    [reorder(xs, order) for xs in a_list]

    【讨论】:

      【解决方案3】:

      我建议这样做,

      import copy
      
      a_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
      order = [1, 0, 2]
      
      lis = copy.deepcopy(a_list)
      
      ind = 0
      for i in range(len(a_list)):
          ind = 0
          for j in order:
              lis[i][ind] = a_list[i][j]
              ind += 1
      
      a_list = lis
      
      print(a_list)
      

      这可能不是最合适的解决方案,
      但我认为你可以这样做。
      谢谢
      祝你好运

      【讨论】:

        猜你喜欢
        • 2014-12-01
        • 2016-12-02
        • 1970-01-01
        • 2021-12-04
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 2019-03-09
        • 1970-01-01
        相关资源
        最近更新 更多