Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: replacing multiple list items by one

I want to write a calculator program. My goal is to replace multiple list items(with datatype str) by one(int). I`ve tryed the insert method, but it creates a new inner list and places it at the end of the main list.

Something like this:

input_list = ['4','5','6','+','8','7','4']

#expected result
output_list = [456, '+', 874]

#actual result
input_list = ['4','5','6','+','8','7','4',['4','5','6']]

I also tryed extend method and also without succeess.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code:

num = ""
start = ""
for x in range(len(list)):
    if list[x].isdigit() == True:
        if start == "":
            start = x    
            num += list[x]
            continue
        else:
            num += list[x]
            continue     
    else:
        num = int(num)
        list.insert(num,list[start:x])
        num = ""
        start = ""
        continue

>Solution :

You can use itertools.groupby and pass str.isdigit to its key. It will group the numbers together.

from itertools import groupby

input_list = ["4", "5", "6", "+", "8", "7", "4"]

result = []
for k, g in groupby(input_list, key=str.isdigit):
    string = "".join(g)
    # It's True for numbers, False for operators.
    if k:
        number = int(string)
        result.append(number)
    else:
        result.append(string)

print(result)

output:

[456, '+', 874]

It’s also possible with list-comprehension:

from itertools import groupby

input_list = ["4", "5", "6", "+", "8", "7", "4"]

result = [
    int("".join(g)) if k else "".join(g)
    for k, g in groupby(input_list, key=str.isdigit)
]

print(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading