[Python-de] Sorting string lists and merging lists

c.schmitt at briefdomain.de c.schmitt at briefdomain.de
Mo Mai 13 14:02:01 CEST 2013


Am Montag, 13. Mai 2013 12:51:37 UTC+2 schrieb Mike Müller:
> Am 13.05.13 12:35, schrieb c.schmitt at briefdomain.de:
> 
> > Hi, I have 2 Lists like this:
> 
> > list1 = ["ML2", "ML4", "ML6", "ML8", "ML10", "ML12"]
> 
> > list2 = ["ML4", "ML6", "ML8", "ML10", "ML12", "ML14", "ML16", "ML18", "ML20"]
> 
> > 
> 
> > Now i want to merge these list and sort out double elements. At the moment i can do this, but i don't think it's that efficient:
> 
> > 
> 
> >         new_list = list1
> 
> > 
> 
> >         for element in list2:
> 
> >             if element not in list1:
> 
> >                 new_list.append(element)
> 
> > 
> 
> > And after that I want to sort the lists that it is sorted after the number like:
> 
> > ML2, ML4, ML6, etc.. (ML is always ML and won't be changed)
> 
> > 
> 
> > Is there a way to do this?
> 
> 
> 
> Sets and sorting with `key` should solve your problem:
> 
> 
> 
> list1 = ["ML2", "ML4", "ML6", "ML8", "ML10", "ML12"]
> 
> list2 = ["ML4", "ML6", "ML8", "ML10", "ML12", "ML14", "ML16", "ML18", "ML20"]
> 
> merged = set(list1).union(set(list2))
> 
> sorted_by_number = sorted(merged, key=lambda x: int(x[2:]))
> 
> print sorted_by_number
> 
> 
> 
> Output:
> 
> ['ML2', 'ML4', 'ML6', 'ML8', 'ML10', 'ML12', 'ML14', 'ML16', 'ML18', 'ML20']
> 
> 
> 
> 
> 
> HTH,
> 
> Mike
> 
> 
> 
> > _______________________________________________
> 
> > python-de maillist  -  python-de at python.org
> 
> > http://mail.python.org/mailman/listinfo/python-de
> 
> >

Thank you. I had something with lambda and key in my mind, but i didn't thought about it.
Still i'm doing the merging now with a distinct in SQL. (Django) With Q, I didn't read that distinct is available in Django ORM aswell, so sorry for that.

Btw. Thank you to all of you. never thought I will get an answer that fast.


Mehr Informationen über die Mailingliste python-de