Hi All,
I've been learning python for some time, and I really like it.
I used this forum many times, and found answers for many of my questions. Unfortunatelly I can't find answer for my current problem:

I have two lists (both the same size) and I need to sort the first one, and then apply changes in order of items to the second list.

I'd be grateful for any suggestions how to do it python-way ;-)
Best regards

Recommended Answers

All 7 Replies

We need some actual examples of your lists and the sort order you want.

sure, I'll try to explain:

labels=['yes','i don't know','no']

the idea is that these lists represents results of the poll, and the labels are "bound" to results i.e. yes was chosen 5 times, no 30 times.
i want to sort results and then sort labels to mirror the order of results, so I'd get:

labels=['yes','no','i don't know']

of course this is just an example, in reality I can have couple of lists with results and labels "bound" together, and I need to sort all of them by one of them.

maybe the whole idea to have two/more lists is wrong, if that's the case I can change it.


You will have to link them some way. You can combine them and sort as below, otherwise you will have to associate "yes" with zero, "i don't know" with one, etc. and reorder the list named results after sorting the labels list, but there isn't any reason why you have to have two separate lists instead one list of lists. You could also use a dictionary of lists, using each element in labels as the key, pointing to a list that contains one or more results, and then sort the keys in what ever order you want.

labels=['yes',"i don't know",'no']
list_3 = zip(labels, results)
print list_3

maybe this will work?

labels=['yes','i dont know','no']
results=[labels[0],labels[1], labels[2]]

EDIT: sorry, i misunderstood the question and this is irrelevant... my fault

You would probably want to make that:

labels=['yes',"i don't know",'no']
list_3 = zip(results, labels)
print list_3

So that it's sorted based on results rather than labels.

But using a dictionary may be a better choice in the first place.

great, thanks, zip did the trick.

You could also use a dictionary with the labels as keys and results as values. Then you can sort the keys and access the value through the dictionary. I think that's cleaner than using three lists. Just my $0.02, though

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.