sort one list using the values from another list

S

Simon Sun

Magnus said:
Is there something here I can't see, or did you just
change a variable name and present that as another
solution?
Heh, I have use python for a very short time. Base your statements, I test
in python, found `_' is a valid variable name. So I don't know it is a just
a plain variable or like something pattern matching in Haskell.
 
K

Kent Johnson

Simon said:
Heh, I have use python for a very short time. Base your statements, I test
in python, found `_' is a valid variable name. So I don't know it is a just
a plain variable or like something pattern matching in Haskell.

_ is just a plain variable name in Python. It is sometimes when a
variable is needed to receive a value that won't be used. So your
example was correct and idiomatic but functionally identical to mine.

Kent
 
B

bearophileHUGS

_ is just a plain variable name in Python. It is sometimes when a variable is needed to receive a value that won't be used.<

Like in some other interactive systems (Mathematica, etc, but with a
different syntax) _ has a use in the interactive shell, it contains the
last unassigned result:
Traceback (most recent call last):
10

Bye,
bearophile
 
R

Ron Adam

Following Ron Adam solution (and using [] instead of list() in the last
line), this may be a possible solution of the problem, that is often
quite fast:

def psort16(s1, s2):
try:
d = dict(izip(s2, s1))
except TypeError:
_indices = range(len(s1))
_indices.sort(key=s2.__getitem__)
s1[:] = map(s1.__getitem__, _indices)
else:
if len(d) == len(s1):
s1[:] = [d[v] for v in sorted(d)]
else:
_indices = range(len(s1))
_indices.sort(key=s2.__getitem__)
s1[:] = map(s1.__getitem__, _indices)

Bye,
bearophile

Looks good, but I think It would be simpler to just do.

def psort17(s1, s2):
try:
d = dict(izip(s2, s1))
assert len(d) != len(s2)
s1[:] = [d[v] for v in sorted(d)]
except Exception:
_indices = range(len(s1))
_indices.sort(key=s2.__getitem__)
s1[:] = map(s1.__getitem__, _indices)

We don't need to specify which exception. Any problems will just get
raised again on the second try it also fails.

Cheers,
Ron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top