Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
69 views
in Technique[技术] by (71.8m points)

python - 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!

question from:https://stackoverflow.com/questions/65918866/subtract-string-list-elements-from-2-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...