当我在某个列
的函数中按字母顺序对结构进行排序时,我的代码出现问题例如我有:
name: Bela message: abc priority: 1
name: Carla message: efg priority: 0
name: Ana message: xyz priority: 0
输出必须是这样的:
name: Ana message: xyz priority: 0
name: Bela message: abc priority: 1
name: Carla message: efg priority: 0
我的代码是这样的:
class structura:
prioritate = 0
destinatar = ""
continut = ""
n = input("mesaje maxime: ");
cutie = [structura() for i in range(n)]
for i in range(n):
print "\nAdaugare mesaj %d" %(i + 1)
cutie[i].prioritate= input("Prioritate mesaj :")
cutie[i].destinatar = raw_input("Destinatar mesaj: ")
cutie[i].continut = raw_input("Continut mesaj: ")
i=0
while i<n-1:
if cutie[i].prioritate==0:
if cutie[i].destinatar>cutie[i+1].destinatar:
cutie[i].destinatar,cutie[i+1].destinatar=cutie[i+1].destinatar,cutie[i].destinatar
cutie[i].continut,cutie[i+1].continut=cutie[i+1].continut,cutie[i].continut
i=0
print i
else:
i+=1
else:
i+=1
for i in range(n):
print "cutie: prioritate= %d | destinatar= %s | continut= %s" %(cutie[i].prioritate, cutie[i].destinatar, cutie[i].continut)
但是使用这种排序代码它并不起作用(它只是cutie.destinatar,而不是cutie.destintar和cutie.continut):
i=0
while i<n-1:
if cutie[i].prioritate==0:
if cutie[i].destinatar>cutie[i+1].destinatar:
cutie[i].destinatar,cutie[i+1].destinatar=cutie[i+1].destinatar,cutie[i].destinatar
cutie[i].continut,cutie[i+1].continut=cutie[i+1].continut,cutie[i].continut
i=0
print i
else:
i+=1
else:
i+=1
我也尝试使用排序函数,但它不适用于我的结构形式。有解决方案吗?
答案 0 :(得分:1)
您希望根据属性对对象进行排序。 sorted
接受key
参数,该参数是您要对其进行排序的值。
my_sorted_list = sorted(cutie, key = lambda x: x.destinatar)