Home > Mobile >  Python: replacing multiple list items by one
Python: replacing multiple list items by one

Time:10-23

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

CodePudding user response:

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

CodePudding user response:

I woudn't recommend replacing values in the input_list as list manipulation is one of the most hard and finicky things you can do.
Also never name a list list, because list normally means the list type. (you can see that by the syntax highlighting).
If you use an output list, then the start variable becomes redundant Here is the fixed code:

input_list = ['4','5','6',' ','8','7','4']
output_list = []
num = ""
for x in range(len(input_list)):
    if input_list[x].isdigit() == True: # check if char x is a digit
        num  = input_list[x] # add to num
    elif num == "": # num is empty so add the char directly to output_list
        output_list.append(input_list[x])
    else: # add num to output_list
        output_list.append(int(num))
        num = ""
        output_list.append(input_list[x]) # add the current char (which wasn't a digit back to the output_list)
if num != "": # add the last number
    output_list.append(int(num))
print(output_list)
> [456, ' ', 874]

CodePudding user response:

The issue is with list.insert(num,list[start:x]). You are inserting the result into your input list, list itself. You should create an empty list and insert the results in it. I also suggest using output_list.append(num) instead, when adding num to your output list.

CodePudding user response:

try this:

endChars = "/* - "
output = []
temp = ""

for char in input_list:

        if char not in endChars:

            temp  = char

        else:

            if temp != " ":
            
                output.append(temp)
 
            if char != " "

                output.append(char)

            temp = ""

output.append(temp)

print(output)
  • Related