1

I have a problem with my code when I sort my struct alphabetically in the function of some column

For example I have:

name: Bela message: abc priority: 1
name: Carla message: efg priority: 0
name: Ana message: xyz priority: 0

And the output needs to be like this:

name: Ana message: xyz priority: 0
name: Bela message: abc priority: 1
name: Carla message: efg priority: 0

My code is like this:

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)

But with this sorting code it's doesn't work(it's sort just cutie.destinatar only, instead of cutie.destintar and 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

I tried with the sorted function too, but it doesn't work with my struct form. Is there a solution?

1 Answer 1

1

You want to sort the objects according to an attribute. sorted accepts a key parameter, which is the value according to which you want to sort.

my_sorted_list = sorted(cutie, key = lambda x: x.destinatar)
Sign up to request clarification or add additional context in comments.

4 Comments

i tryed but it's doens't sort with my struct class
sorted does not sort the list in-place, it returs a new one. edited the answer
yes, it's work now, thanks for help, one day in documentation for such a simple solution
key=operator.itemgetter('destinatar') would be faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.