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函数
首先,您需要将
L
从2D
数组转换为以下格式的字典这将使我们更容易访问感兴趣的
name
,然后使用sorted(list(L2))
按字母顺序排序要转换为上述格式的词典,只需执行以下操作
然后我们可以通过将L2转换为一个列表来缩短L2,然后循环遍历已排序的列表并按顺序重新创建第一个
L
列表最后,通过调用
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in L]))
,您可以很好地打印它们。输出现在,您可以将其全部封装在一个函数中,如下所示
相关问题 更多 >
编程相关推荐