I want to write a calculator program. My goal is to replace multiple list items(with datatype str
) by one(int
). I've tried 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 tried extend method and also without success.
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
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)
Note: I intentionally wrote two "".join(g)
inside the list-comprehension. Because I had to. Don't try using walrus because you won't get your expected result:
result = [
int((s := "".join(g))) if k else s
for k, g in groupby(input_list, key=str.isdigit)
]
the (s := "".join(g))
part is only evaluated when the k
is True
, not always. That means if k
is False
, you'll get the previous value of s
which is evaluated in the previous iteration which is '456'
.