Home > Enterprise >  Combining continuous new lines based on a list in Python
Combining continuous new lines based on a list in Python

Time:08-30

I am trying to create a function that will continuous new lines based on a list in Python. For example, I have a list: enter image description here

I want my function to output this: enter image description here

I have a function already however its output is wrong:

final_list = list()
for sentence in test:
    if sentence != "\r\n":
        print(sentence)
        final_list.append(sentence)
    else:
        #Check if the next sentence is a newline as well
        curr_idx = test.index(sentence)
        curr_sentence = sentence
        next_idx = curr_idx   1
        next_sentence = test[next_idx]
        times = 0
        while next_sentence == "\r\n":
            times  = 1
            combine_newlines = next_sentence * times
            next_idx  = 1
            next_sentence = test[next_idx]
            continue
        final_list.append(combine_newlines  "\r\n")      

enter image description here

Thank you very much!

CodePudding user response:

You can use itertools.groupby to group consecutive items of the same value, and then join the grouped items for output:

from itertools import groupby

print([''.join(g) for _, g in groupby(test)])

CodePudding user response:

test = [
    'I will be out',
    'I will have limited',
    '\r\n',
    '\r\n',
    '\r\n',
    'Thanks,',
    '\r\n',
    'Dave',
    '\r\n',
    '\r\n',
]

final_list = []
for e in test:
    if e != '\r\n':
        final_list.append(e)
    else:
        if len(final_list) == 0 or not final_list[-1].endswith('\r\n'):
            final_list.append(e)
        else:
            final_list[-1]  = e

prints

['I will be out', 'I will have limited', '\r\n\r\n\r\n', 'Thanks,', '\r\n', 'Dave', '\r\n\r\n']

Explanation: Iterate over your items e in test, if they are not equal to \r\n, simply append them to the final_list, otherwise either append them to final_list or extend the last element in final_list based on if it ends with \r\n.

CodePudding user response:

test = [ 'I will be out', 'I will have limited', '\r\n', '\r\n', '\r\n', 'Thanks,', '\r\n', 'Dave', '\r\n', '\r\n', ]

final_list = [] for e in test: if e != '\r\n': final_list.append(e) else: if len(final_list) == 0 or not final_list[-1].endswith('\r\n'): final_list.append(e) else: final_list[-1] = e

  • Related