Issue
I have two lists that I am trying to join. They two become one. A partial match between the values is used to merge the values.
list1 = ["15:09.123", "15:09.234", "15:09.522", "15:09.621", "15:10.123", "15:11.123", "15:12.123", "15:12.987"]
list2 = ["15:09", "15:09", "15:10", "15:14"]
final = []
for each in list2:
for each1 in list1:
if each in each1:
eachtemp = each1.split(".")[1]
final.append(each+"."+eachtemp)
list1.remove(each1)
print(final)
This produces an output
['15:09.123', '15:09.522', '15:09.234', '15:10.123']
But ideal output I want is
['15:09.123', '15:09.234', '15:10.123', '15:14.000']
It should not contain "15:09.522", "15:09.621"
even though they have partially matching elements in the list1. The final list should contain all elements in list2
with 3 more digits acquired from list1 and final
list should be the same length as list2
.
Solution
I might suggest using an iterator over list1
and consuming elements from it as you iterate over list2
(renaming these ms_list
and s_list
to make it easier to keep track of which is which):
>>> ms_list = ["15:09.123", "15:09.234", "15:09.522", "15:09.621", "15:10.123", "15:11.123", "15:12.123", "15:12.987"]
>>> s_list = ["15:09", "15:09", "15:10", "15:14"]
>>> final = []
>>> ms_iter = iter(ms_list)
>>> for s in s_list:
... default = f"{s}.000"
... ms = next(ms_iter, default)
... while not ms.startswith(s) and ms < s:
... ms = next(ms_iter, default)
... final.append(ms if ms.startswith(s) else default)
...
>>> final
['15:09.123', '15:09.234', '15:10.123', '15:14.000']
Answered By - Samwise
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.