漂亮地打印2d矩阵,同时调用排序函数

2024-09-22 16:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我怎样才能做出这样一个漂亮的打印,并同时调用我的函数,从而使输出变得漂亮和有序?这是我第一次编写这样的代码,我搞不懂


Tags: inforcellrangejoinkevinannasophie
1条回答
网友
1楼 · 发布于 2024-09-22 16:27:01

你的问题是排序功能,漂亮的打印工作正常。这里有一种方法可以完成第一步,无需重新发明轮子,使用本地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转换为一个列表来缩短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]))

相关问题 更多 >