簡體   English   中英

按行對列表列表進行垂直排序

[英]sort a list of lists by row, vertically

對編碼非常陌生,想要比較列表列表中的相同索引,以便垂直對齊數字,使它們按數字順序排列:

編寫一個名為 sort_by_direction 的 function,它接受兩個參數。 第一個稱為 seq 的參數將是列表的列表,其中列表的數量等於每個列表中的項目數。 第二個名為 direc 的參數將給出對每個列表進行排序的方向。 direc 將有四個可能的值,“L”將按升序對每一行進行排序,“R”將按降序對每一行進行排序,“U”對每一列按升序排序,“D”對每一列排序按降序排列。

example = [[3, 6, 1], [5, 2, 2], [0, 8, 7]]
sort_by_direction(example, 'L') # should return [[1, 3, 6], [2, 2, 5], [0, 7, 8]]

example = [[3, 6, 1], [5, 2, 2], [0, 8, 7]]
sort_by_direction(example, 'R') # should return [[6, 3, 1], [5, 2, 2], [8, 7, 0]]

example = [[3, 6, 1], [5, 2, 2], [0, 8, 7]]
sort_by_direction(example, 'U') # should return [[5, 8, 7], [3, 6, 2], [0, 2, 1]]

[[5, 8, 7],

 [3, 6, 2],

 [0, 2, 1]]

example = [[3, 6, 1], [5, 2, 2], [0, 8, 7]]
sort_by_direction(example, 'D') # should return [[0, 2, 1], [3, 6, 2], [5, 8, 7]]

[[0, 2, 1],

 [3, 6, 2],

 [5, 8, 7]]

def sort_by_direction(seq,direc):
    new = []
    if direc == 'L':
        for lst in seq:
            lst.sort()
            new.append(lst)
    elif direc == 'R':
        for lst in seq:
            lst.sort()
            lst.reverse()
            new.append(lst)
    elif direc == 'U':
        for lst in seq:
            for idx, num in enumerate(zip(lst)):
            ????

對每一行進行排序很簡單。

上升:

[sorted(x) for x in example]

降序:

[sorted(x, reverse = True) for x in example]

要按列排序,您可以先轉置嵌套列表,然后按照與上所示相同的方式排序,然后轉回。 轉置列表列表的簡單方法:

transposed = list(zip(*example))

然后,對其進行排序並轉回:

tmp = [sorted(x, reverse = True) for x in transposed]
result = list(zip(*tmp))

當然,它已經出現在“辛普森一家” NumPy 中:

import numpy
example = numpy.array([[3, 6, 1], [5, 2, 2], [0, 8, 7]])
result = numpy.sort(example, axis = 0) # only use axis = 0 to sort vertically
# add this to reverse the order:
result = numpy.flip(result, axis = 0) # only use axis = 0 if sorted vertically

您可以為此使用 pandas :

def sort_by_direction(seq,direc):
    new = []
    if direc == 'L':
        for lst in seq:
            lst.sort()
            new.append(lst)
    elif direc == 'R':
        for lst in seq:
            lst.sort()
            lst.reverse()
            new.append(lst)
    elif direc == 'U':
         df = pd.DataFrame(data=seq)
         k = df.apply(lambda x: (x.sort_values(ascending=False)).to_list(),axis=0)
         return k.values
    
    elif direc == 'D':
         df = pd.DataFrame(data=seq)
         k = df.apply(lambda x: (x.sort_values(ascending=True)).to_list(),axis=0)
         return k.values
        
example = [[3, 6, 1], [5, 2, 2], [0, 8, 7]]
sort_by_direction(example, 'D') 

結果:

array([[0, 2, 1],
       [3, 6, 2],
       [5, 8, 7]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM