473,320 Members | 1,939 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How do I sort these?

I have two lists.
I want to sort by a value in the first list and have the second list
sorted as well... Any suggestions on how I should/could do this?

Oct 28 '05 #1
15 1939
KraftDiner wrote:
I have two lists.
I want to sort by a value in the first list and have the second list
sorted as well... Any suggestions on how I should/could do this?


I guess you mean that you have two lists of same size where each index
position pointing to corrsponding items - like two excel columns? Then
this helps:

sl = zip(list_a, list_b)
sl.sort()
list_a, list_b = unzip(*sl)

Regards,

Diez
Oct 28 '05 #2
KraftDiner wrote:
I have two lists.
I want to sort by a value in the first list and have the second list
sorted as well... Any suggestions on how I should/could do this?
first = [1, 3, 5, 7, 9, 2, 4, 6, 8]
second = ['one', 'three', 'five', 'seven', 'nine', 'two', 'four', 'six', 'eight'] both = zip(first, second)
both.sort()
[b[0] for b in both] [1, 2, 3, 4, 5, 6, 7, 8, 9] [b[1] for b in both] ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']


You mean like this?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Oct 28 '05 #3
yes... Thats the idea...

Oct 28 '05 #4
In C++ you can specify a comparision method, how can I do this with
python...
Say for instance the first list was a dictionary and I wanted to sort
on one of the keys in the dictionary?

Oct 28 '05 #5
unzip doesn't seem to work for me...

Oct 28 '05 #6
"KraftDiner" <bo*******@yahoo.com> writes:
In C++ you can specify a comparision method, how can I do this with
python...


Yes, see the docs. Just pass a comparison func to the sort method.
Oct 28 '05 #7
> unzip doesn't seem to work for me...

It's not a part of the standard Python distribution, but this is a
naive implementation (it doesn't react well to the list's contents
having different lengths).

def unzip(seq):
result = [[] for i in range(len(seq[0]))]
for item in seq:
for index in range(len(item)):
result[index].append(item[index])
return result
unzip(zip(range(5), 'abcde'))

[[0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e']]

Oct 28 '05 #8
Sam Pointon a écrit :
unzip doesn't seem to work for me...

It's not a part of the standard Python distribution, but this is a
naive implementation (it doesn't react well to the list's contents
having different lengths).

def unzip(seq):
result = [[] for i in range(len(seq[0]))]
for item in seq:
for index in range(len(item)):
result[index].append(item[index])
return result

unzip(zip(range(5), 'abcde'))
[[0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e']]


unzip() could be also be written like this:

def unzip(seq):
return zip(*seq)

Faster and nicer, isn't it?

Except that it returns a list of tuples:
unzip(zip(range(5), 'abcde'))

[(0, 1, 2, 3, 4), ('a', 'b', 'c', 'd', 'e')]

--
Amaury
Oct 28 '05 #9
On Fri, 28 Oct 2005 13:42:49 -0700, KraftDiner wrote:
unzip doesn't seem to work for me...


Nor for me:
unzip

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'unzip' is not defined
I don't think it exists.

But it is easy enough to create:

def unzip(L):
"""Reverse a zip.

Expects L to be a list of the form:
[(1, 'a'), (2, 'b'), (3, 'c')]
and returns:
[(1, 2, 3), ('a', 'b', 'c')]

Note that unzip(zip(seq1, seq2)) is not quite a null-op,
because some type information is lost, e.g. lists and
strings are converted into tuples.
"""
return zip(*L)

As you can see, the documentation for unzip is longer than the code itself :-)

--
Steven.

Oct 29 '05 #10
Paul Rubin <http://ph****@NOSPAM.invalid> wrote:
"KraftDiner" <bo*******@yahoo.com> writes:
In C++ you can specify a comparision method, how can I do this with
python...


Yes, see the docs. Just pass a comparison func to the sort method.


Or, better, pass a key-extraction function, that's much handier and
faster (it automates the "decorate-sort-undecorate", DSU, idiom).
Alex
Oct 29 '05 #11
KraftDiner wrote:
unzip doesn't seem to work for me...


Mrmpf, my bad. The operation is called unzip, but implpemented by using
zip - so
unzip(l) == zip(*l)
So the exchange unzip with zip in my example.

Diez
Oct 29 '05 #12
On Fri, 28 Oct 2005 20:00:42 +0100, Steve Holden <st***@holdenweb.com> wrote:
KraftDiner wrote:
I have two lists.
I want to sort by a value in the first list and have the second list
sorted as well... Any suggestions on how I should/could do this?
first = [1, 3, 5, 7, 9, 2, 4, 6, 8]
second = ['one', 'three', 'five', 'seven', 'nine', 'two', 'four','six', 'eight'] both = zip(first, second)
both.sort()
[b[0] for b in both][1, 2, 3, 4, 5, 6, 7, 8, 9] [b[1] for b in both]['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
You mean like this?

ISTM there could be a subtle requirement in the way the OP stated what he wanted to do.
I.e., it sounds like he would like to sort the first list and have a second list undergo
the same shuffling as was required to sort the first. That's different from having the
data of the second participate in the sort as order-determining data, if equals in the
first list are not to be re-ordered:
first = [2]*5 + [1]*5
first [2, 2, 2, 2, 2, 1, 1, 1, 1, 1] sorted(first) [1, 1, 1, 1, 1, 2, 2, 2, 2, 2] second = [chr(ord('A')+i) for i in xrange(9,-1,-1)]
second ['J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A'] sorted(second) ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

Now the zipped sort unzipped: zip(*sorted(zip(first,second))) [(1, 1, 1, 1, 1, 2, 2, 2, 2, 2), ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J')]

Now suppose we sort the first and use the elements' indices to preserve order where equal sorted((f,i) for i,f in enumerate(first)) [(1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]

Separate out the first list elements: [t[0] for t in sorted((f,i) for i,f in enumerate(first))] [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]

Now select from the second list, by first-element position correspondence: [second[t[1]] for t in sorted((f,i) for i,f in enumerate(first))]

['E', 'D', 'C', 'B', 'A', 'J', 'I', 'H', 'G', 'F']

Which did the OP really want? ;-)

Regards,
Bengt Richter
Oct 30 '05 #13
Bengt Richter wrote:
On Fri, 28 Oct 2005 20:00:42 +0100, Steve Holden <st***@holdenweb.com>
wrote:
KraftDiner wrote:
I have two lists.
I want to sort by a value in the first list and have the second list
sorted as well... Any suggestions on how I should/could do this?

>>> first = [1, 3, 5, 7, 9, 2, 4, 6, 8]
>>> second = ['one', 'three', 'five', 'seven', 'nine', 'two', 'four',

'six', 'eight']
>>> both = zip(first, second)
>>> both.sort()
>>> [b[0] for b in both]

[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [b[1] for b in both]

['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
>>>


You mean like this?

ISTM there could be a subtle requirement in the way the OP stated what he
wanted to do. I.e., it sounds like he would like to sort the first list
and have a second list undergo the same shuffling as was required to sort
the first. That's different from having the data of the second participate
in the sort as order-determining data, if equals in the first list are not
to be re-ordered:
>>> first = [2]*5 + [1]*5
>>> first [2, 2, 2, 2, 2, 1, 1, 1, 1, 1] >>> sorted(first) [1, 1, 1, 1, 1, 2, 2, 2, 2, 2] >>> second = [chr(ord('A')+i) for i in xrange(9,-1,-1)]
>>> second ['J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A'] >>> sorted(second) ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

Now the zipped sort unzipped: >>> zip(*sorted(zip(first,second))) [(1, 1, 1, 1, 1, 2, 2, 2, 2, 2), ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
['I', 'J')]

Now suppose we sort the first and use the elements' indices to preserve
order where equal >>> sorted((f,i) for i,f in enumerate(first)) [(1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 0), (2, 1), (2, 2), (2, 3),
[(2, 4)]

Separate out the first list elements: >>> [t[0] for t in sorted((f,i) for i,f in enumerate(first))] [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]

Now select from the second list, by first-element position correspondence: >>> [second[t[1]] for t in sorted((f,i) for i,f in enumerate(first))] ['E', 'D', 'C', 'B', 'A', 'J', 'I', 'H', 'G', 'F']

Which did the OP really want? ;-)


I don't know, but there certainly is no subtle requirement to not provide
the key argument:
import operator
first = [2]*5 + [1]*5
second = list(reversed("ABCDEFGHIJ"))
[s for f, s in sorted(zip(first, second))] ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] [s for f, s in sorted(zip(first, second), key=operator.itemgetter(0))]

['E', 'D', 'C', 'B', 'A', 'J', 'I', 'H', 'G', 'F']

Peter

Oct 30 '05 #14
# This can be a solution:

from operator import itemgetter
seq1a = ([2] * 4) + ([1] * 4)
seq2a = [complex(3-el,7-el) for el in range(1, 9)]
assert len(seq1a) == len(seq2a)
print seq1a, seq2a, "\n"

mix = zip(seq1a, seq2a)
# mix.sort() # Not possible
mix.sort(key=itemgetter(0))

# If you need tuples output:
seq1b, seq2b = zip(*mix)
print seq1b, seq2b, "\n"

# Alternative, lists output:
seq1b = [el[0] for el in mix]
seq2b = [el[1] for el in mix]
print seq1b, seq2b, "\n"

Bye,
bearophile

Oct 30 '05 #15
On Sun, 30 Oct 2005 10:13:42 +0100, Peter Otten <__*******@web.de> wrote:
Bengt Richter wrote:

[...]
Now select from the second list, by first-element position correspondence:
>>> [second[t[1]] for t in sorted((f,i) for i,f in enumerate(first))]

['E', 'D', 'C', 'B', 'A', 'J', 'I', 'H', 'G', 'F']

Which did the OP really want? ;-)


I don't know, but there certainly is no subtle requirement to not provide
the key argument:
import operator
first = [2]*5 + [1]*5
second = list(reversed("ABCDEFGHIJ"))
[s for f, s in sorted(zip(first, second))]['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] [s for f, s in sorted(zip(first, second), key=operator.itemgetter(0))]

['E', 'D', 'C', 'B', 'A', 'J', 'I', 'H', 'G', 'F']

D'oh yeah, forgot about key ;-/ (and this kind of problem probably at least
partly motivated its introduction, so it should have jumped to mind).
Thanks, your version is much cleaner ;-)

Regards,
Bengt Richter
Oct 30 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: lawrence | last post by:
Is there an easy way to sort a 2 dimensional array alphabetically by the second field in each row? Also, when I use sort() on a two dimensional array, it seems to work a lot like...
40
by: Elijah Bailey | last post by:
I want to sort a set of records using STL's sort() function, but dont see an easy way to do it. I have a char *data; which has size mn bytes where m is size of the record and n is the...
15
by: David | last post by:
sorry for the last post, itchy fingers. I'm having a bit of difficulty sorting images named in sequential numerical order. Here are the image names and how I need them sorted. image1.jpg...
20
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort†method. For example: ...
11
by: James P. | last post by:
Hello, I have a report with the Priority field is used as sort order and grouping. The problem is the data in this Priority field if sorted in ascending order is: High, Low, and Medium. How...
25
by: Rainmaker | last post by:
Hi, Can anyone tell me an efficient algorithm to sort an array of strings? Keep in mind that this array is HUGE and so the algorithm should me efficient enough to deal with it. Thanks
4
by: Matt | last post by:
I have been searching all over the web for a way to sort a DataGridView based on the actual text being shown in a ComboBox column as opposed to the underlying value (an ID in this case). Can anyone...
11
by: Jeff Schwab | last post by:
Would std::sort ever compare an object with itself? I'm not talking about two distinct, equal-valued objects, but rather this == &that. The container being sorted is a std::vector. I've never...
3
by: aRTx | last post by:
I have try a couple of time but does not work for me My files everytime are sortet by NAME. I want to Sort my files by Date-desc. Can anyone help me to do it? The Script <? /* ORIGJINALI
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.