Sort not identical lists Python
I have two lists.
One list contains only codes e.g.:
b3b 3cd 6f6 4d8 96b 00a 774 eb3 607 7e5
The other list contains code with names e.g.
b3b:John 607:Eric 7e5:Jarrold
But the list is not compleet yet.
What I want as output, because the other cannot be removed and has to be in the right order, e.g.
b3b:John 3cd 6f6 4d8 96b 00a 774 eb3 607:Eric 7e5:Jarrold
Already have this code but it only returns True or False but that's not what I want.
list1 = [line.strip() for line in open('list1')] list2 = [line.strip() for line in open('list2')] comp = [i[:3] for i in list2] for i in list1: print(i, i in list2)
Maybe anyone who can help me with this?
You should use a dictionary mapping keys to names instead of a list as the second data structure:
with open("list1") as f: keys = [line.strip() for line in f] with open("list2") as f: names = dict(line.strip().split(":", 1) for line in f)
Now you can efficiently implement your loop:
for k in keys: print(k, names.get(k, ""))
Performing a linear search in list2 for every entry of list1 would be rather inefficient. Apart from the better performance, a dictionary is also a better model of the meaning of your data.