Python入门题045:根据对象属性进行排序

Python014

Python入门题045:根据对象属性进行排序,第1张

定义一个Student类,包含name和age。对于一个包含Student对象列表,按 age 属性进行排序。

#python #class类 #对象属性 #排序

Python入门题045:根据对象属性进行排序

代码1:

代码2:

不对,应该是:

for i in range(0, len(L)-1):

for j in range(i+1, len(L)):

if L[i] >L[j]:

L[i], L[j] = L[j], L[i]

print(L)

以上程序的意思是:首先遍历整个列表,如果当前元素大于下一个元素,那么交换它们的位置。这样就可以实现对列表的升序排序了。

s = [9, 2, -4, 7, -1, 0, 5, -2, -5]

def sort_abs(s):

s2 = []

for i in s:

s2.append(abs(i))

s2.sort()

for j in range(len(s2)):

try:

if s2[j] == s2[j + 1]:

s2[j] = -s2[j]

except:

break

return s2

print(s)

print(sort_abs(s))