[Python] How to delete element from python list in loop over this list [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have time segments in list such as:
    [{'start': 12.4, 'end': 12.8}, {'start': 14.0, 'end': 15.5}, {'start': 15.7, 'end': 16.2}, {'start': 16.5, 'end': 17.1}, {'start': 17.9, 'end': 18.5}, {'start': 20.5, 'end': 21.0}, {'start': 22.1, 'end': 22.4}, {'start': 23.0, 'end': 23.7}, {'start': 24.9, 'end': 27.8}, {'start': 29.2, 'end': 34.0}, {'start': 34.5, 'end': 35.4}, {'start': 36.5, 'end': 37.1}, {'start': 37.7, 'end': 38.5}, {'start': 38.7, 'end': 40.4}, {'start': 43.5, 'end': 44.3}, {'start': 45.2, 'end': 48.1}, ]

    And write function which combine time segments if his distance less then chunk_size.

    def combineTimeSegments(segmentsList, chunk_size: int = 2):

    segments=[]
    segments[:] = segmentsList
    counter = 0
    while(counter < len(segments)):
    try:
    cur_segment = segments[counter]
    next_segment = segments[counter+1]
    diff_length_segment=cur_segment['end']-cur_segment['start']
    length_between_segments=next_segment['start']-cur_segment['end']
    if length_between_segments <= chunk_size:
    cur_segment['end']=next_segment['end']
    new_segments = [seg for seg in segments if seg!=next_segment]
    segments.clear()
    segments[:] = new_segments
    counter=counter-1
    if counter < 0:
    counter = 0
    continue
    else:
    if diff_length_segment < chunk_size:
    cur_segment['end']=cur_segment['start']+chunk_size
    except Exception as err:
    pass
    counter += 1

    return segments


    I take right result of combining segments: [{'start': 12.4, 'end': 40.4}, {'start': 43.5, 'end': 48.1}]

    But changing original list only in first segment. Please help me, what I make wrong? [{'start': 12.4, 'end': 40.4}, {'start': 14.0, 'end': 15.5}, {'start': 15.7, 'end': 16.2}, {'start': 16.5, 'end': 17.1}, {'start': 17.9, 'end': 18.5}, {'start': 20.5, 'end': 21.0}, {'start': 22.1, 'end': 22.4}, {'start': 23.0, 'end': 23.7}, {'start': 24.9, 'end': 27.8}, {'start': 29.2, 'end': 34.0}, {'start': 34.5, 'end': 35.4}, {'start': 36.5, 'end': 37.1}, {'start': 37.7, 'end': 38.5}, {'start': 38.7, 'end': 40.4}, {'start': 43.5, 'end': 48.1}, {'start': 45.2, 'end': 48.1}]

    Continue reading...

Compartilhe esta Página