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.
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)