简体   繁体   中英

Subtract String List Elements from 2 lists

I have the following code, which works fine for adding string elements from 2 lists:

list_1 = ['2 Red', '8 Blue', '4 Green']
list_2 = ['10 Red', '2 Blue', '3 Green']

list_1.extend(list_2)

results = {}

for elem in list_1:
    number, color = elem.split()
    results[color] = results.get(color, 0) + int(number)

result = [f"{i} {p}" for i, p in zip(results.values(), results.keys())]

Output: ['12 Red', '10 Blue', '7 Green']

Now, I want to do basic subtraction for the same elements, that the output is as follows:

Output: ['8 Red', '6 Blue', '1 Green']

I thought I understood my code, but obviously I don't, I get stuck with the + operator for int(numbers) & I do not understand the zip() function. I hope you guys can help me.

Stay healthy and have a nice day!

We use int for addition since the data to add is a string after the split operation.

Secondly, we use zip method to iterate the dictionary elements together in a single loop.

Further, you can use abs function to get the absolute value for the second part of the problem:

list_1 = ['2 Red', '8 Blue', '4 Green']
list_2 = ['10 Red', '2 Blue', '3 Green']
list_1.extend(list_2)

results = {}

for elem in list_1:
    number, color = elem.split()
    results[color] = abs(int(number) - results.get(color, 0) )

result = [f"{i} {p}" for i, p in zip(results.values(), results.keys())]

print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM