Sorting string lists and merging lists

13/05/2013 - 12:35 von c.schmitt | Report spam
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?
 

Lesen sie die antworten

#1 Mike Müller
13/05/2013 - 12:51 | Warnen spam
Am 13.05.13 12:35, schrieb :
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 -
http://mail.python.org/mailman/listinfo/python-de

Ähnliche fragen