漂亮地打印二维矩阵并同时调用排序函数

pretty print 2d matrix and call a sorting function at the same time

L = [['kevin', 8.5, 17.1, 5.9, 15.0, 18], ['arsene', 7.1, 4.4, 15.0, 5.6, 18], ['toufik', 1.1, 2.2, 13.4, 3.1, 20], ['lubin', 16.3, 14.8, 13.1, 5.6, 20], ['yannis', 18.8, 2.4, 12.0, 8.0, 18], ['aurelie', 3.6, 18.8, 8.2, 18.2, 18], ['luna', 14.6, 11.5, 15.2, 18.5, 19], ['sophie', 7.4, 2.1, 18.1, 2.9, 19], ['shadene', 17.9, 7.1, 16.7, 2.5, 19], ['anna', 9.7, 12.8, 10.6, 6.9, 20]]


def triNom(L):
'''sorts names alphabetically'''
n = len(L)
for i in range(n):
    for j in range (n - i - 1):
        if L[j] > L[j + 1]:
            L[j], L[j + 1] = L[j + 1], L[j]
return L

print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in L]))

Output :

kevin   8.5     17.1    5.9     15.0    18
arsene  7.1     4.4     15.0    5.6     18
toufik  1.1     2.2     13.4    3.1     20
lubin   16.3    14.8    13.1    5.6     20
yannis  18.8    2.4     12.0    8.0     18
aurelie 3.6     18.8    8.2     18.2    18
luna    14.6    11.5    15.2    18.5    19
sophie  7.4     2.1     18.1    2.9     19
shadene 17.9    7.1     16.7    2.5     19
anna    9.7     12.8    10.6    6.9     20

我怎样才能像这样制作漂亮的打印并同时调用我的函数,以便输出漂亮且排序?这是我第一次编写这样的代码,我无法理解。

您的问题与排序功能有关,漂亮的打印工作正常。这是第一种方法,无需重新发明轮子,使用 原生 python 函数。

首先,您需要将 L2D 数组转换为以下格式的字典。

L2 = {'kevin': [8.5, 17.1, 5.9, 15.0, 18], 'arsene': [7.1, 4.4, 15.0, 5.6, 18] }

这将使我们更容易访问我们感兴趣的 name,然后我们使用 sorted(list(L2)).

按字母顺序排序

要转换成上述格式的字典,你可以简单地做

L2: dict = {}

for item in L: # In pseudo-code L2[name] = nums
    L2[item[0]] = [i for i in item[1:len(item)]] # item[0] is name and 1:len(item) the rest of the data (the numbers)  

然后我们可以缩短 L2,将其转换为列表,然后循环遍历排序后的列表并重新创建第一个 L 个列表列表。

L = [] # Set this to empty because we are re-transfering the data
SORTED_L2 = sorted(list(L2)) # sort the list of L2 (only the names)
for name in SORTED_L2:
    numbers = L2[name] 
    L.append([name, *numbers]) # * is for unpacking

然后最后通过调用 print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in L])) 你可以漂亮地打印它们。输出

anna    9.7     12.8    10.6    6.9     20
arsene  7.1     4.4     15.0    5.6     18
aurelie 3.6     18.8    8.2     18.2    18
kevin   8.5     17.1    5.9     15.0    18
lubin   16.3    14.8    13.1    5.6     20
luna    14.6    11.5    15.2    18.5    19
shadene 17.9    7.1     16.7    2.5     19
sophie  7.4     2.1     18.1    2.9     19
toufik  1.1     2.2     13.4    3.1     20
yannis  18.8    2.4     12.0    8.0     18

您现在可以像下面这样将其全部包装在一个函数中

def sortL(L):
    # Convert to dictionary for easy access
    L2: dict = {}
    for item in L:
        L2[item[0]] = [i for i in item[1:len(item)]]
    
    SORTED_L2 = sorted(list(L2)) # Sort the names
    L = [] 
    for item in SORTED_L2:
        L.append([item, *L2[item]])
    return L

def SortAndPrettyPrint(L):
    L = sortL(L)
    print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in L]))