I have two list of marker objects:
class Marker():
def __init__(self,marker_number, marker_data):
self.marker_number = marker_number
self.marker_data = marker_data
and what I want to do is this:
>>> existing_markers = [Marker(marker_number=1, marker_data= 'a'),
Marker(marker_number=2, marker_data= 'b'),
Marker(marker_number=3, marker_data= 'c'),
Marker(marker_number=4, marker_data= 'd'),
Marker(marker_number=5, marker_data= 'e'),]
>>> new_markers = [ Marker(marker_number=1, marker_data= 'aa'),
Marker(marker_number=3, marker_data= 'bb'),
Marker(marker_number=5, marker_data= 'cc'),]
>>> interlace_markers(existing_markers, new_markers)
[Marker(marker_number=1, marker_data= 'a'),
Marker(marker_number=2, marker_data= 'aa'),
Marker(marker_number=3, marker_data= 'b'),
Marker(marker_number=4, marker_data= 'c'),
Marker(marker_number=5, marker_data= 'bb'),
Marker(marker_number=6, marker_data= 'd'),
Marker(marker_number=7, marker_data= 'e'),
Marker(marker_number=8, marker_data= 'cc')]
So that when I interlace the markers, markers with the same number in the new_markers list as the original markers list appear after the original marker, but the numbering updates to maintain a numbered sequence. This is my current approach:
def interlace_markers(current_markers_list, new_markers_list):
interlaced_markers = []
#interlace the markers
for existing_marker in current_markers_list:
interlaced_markers.append(existing_marker)
for new_marker in new_markers_list:
if new_marker.marker_number== existing_marker.marker_number:
interlaced_markers.append(new_marker)
#reset the sequence
sequence_index = 1
for marker in interlaced_markers:
marker.marker_number= sequence_index
sequence_index += 1
return interlaced_markers
I have two problems here:
- What is the most pythonic way to do this
- The original list will likely be large ~10k, and created from an
external file, but the new list will be small ~100-300 long, is
there a more efficient way of doing this rather than using lists?
If I understand you properly, I think this is most easily accomplished with simple sorting:
Now if you want to change the numbering, you can do that in a simple loop:
Note that this works because python’s sorting is stable which means that the order isn’t changed if it doesn’t have to be.
This leads to an O(n) + O(nlogn) = O(nlogn) algorithm which isn’t too bad.