[Python-de] Sorting string lists and merging lists
Mike Müller
mmueller at python-academy.de
Mo Mai 13 13:17:06 CEST 2013
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
>
Mehr Informationen über die Mailingliste python-de