c.sc...@briefdomain.de wrote:
> 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)
Put the items into a set:
>>> list1 = ["ML2", "ML4", "ML6", "ML8", "ML10", "ML12"]
>>> list2 = ["ML4", "ML6", "ML8", "ML10", "ML12", "ML14", "ML16", "ML18",
"ML20"]
>>> items = set(list1)
>>> items.update(list2)
>>> items
set(['ML14', 'ML16', 'ML10', 'ML12', 'ML18', 'ML20', 'ML2', 'ML6', 'ML4',
'ML8'])
> 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?
Define a key function that splits a string into numerical and non-numerical
parts:
>>> import re
>>> split = re.compile("(\d+)").split
>>> def key(s):
... parts = split(s)
... parts[1::2] = map(int, parts[1::2])
... return parts
...
['ml', 2, '']
>>> key("ml10")
['ml', 10, '']
Use the key to sort the set into a list:
>>> sorted(items, key=key)
['ML2', 'ML4', 'ML6', 'ML8', 'ML10', 'ML12', 'ML14', 'ML16', 'ML18', 'ML20']