As I mentioned it is possible using the Schwartzian transform that although the idea comes from Perl in Python it can be implemented using zip
.
The idea is simple, zip
is used to obtain the pairs of elements and sorted
is applied to them. This gives us a list with the pairs ordered by the first iterable past to zip
(equal to this element, the following is used).
Once this is done, we unpack the list returned by sorted
and pass all its elements as arguments to zip
to get back two lists using the elements of the tuples. In Python you can unpack an iterable using *
in front of it.
The only complicated thing is to understand the operation of zip
, I think that with a couple of examples it can be clarified better than with words:
>>> a = (1, 2, 3, 4)
>>> b = ('a', 'b', 'c', 'd')
>>> c = list(zip(a, b))
>>> c
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
>>> d, e = zip(*c)
>>> d
(1, 2, 3, 4)
>>> e
('a', 'b', 'c', 'd')
zip(*c)
is equivalent to:
zip((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))
An example of how to order using the previous idea based on your code:
from datetime import date
# Las dos listas originales
CODIGOS = [1, 2, 3, 4, 5]
FECHAS = [date(2017, 7, 24), date(2017, 7, 25), date(2017, 7, 26), date(2017, 7, 27), date(2017, 7, 28)]
# Concatenas nuevos valores
CODIGOS.extend([7, 10, 24, 14])
FECHAS.extend([date(2017, 7, 30), date(2017, 7, 20), date(2017, 8, 1), date(2017, 7, 21)])
# Ordenamos aplicando lo explicado antes
FECHAS, CODIGOS = map(list, zip(*sorted(zip(FECHAS, CODIGOS))))
Exit:
> > > DATES
[datetime.date (2017, 7, 20), datetime.date (2017, 7, 21), datetime.date (2017, 7, 24), datetime.date (2017, 7, 25), datetime.date (2017) , 7, 26), datetime.date (2017, 7, 27), datetime.date (2017, 7, 28), datetime.date (2017, 7, 30), datetime.date (2017, 8, 1)]
> > > CODES
[10, 14, 1, 2, 3, 4, 5, 7, 24]
If you notice use list.extend
to concatenate the lists, consider using this in your code instead of the cycle for
and append
that you use now.