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
236 views
in Technique[技术] by (71.8m points)

python - Find common values from 2 list of tuples and add the values from one tuple to another

I have 2 lists with tuples as their elements. One element of tuple is to be matched to the tuple from other list and corresponfing values are to be added from one tuple to another.

My 2 lists are :

l1 = [('Receipt total', 10),('Total Amount (AED)', 10),('Grand total', 10),('Net Amount', 9),
 ('Total Amount', 9),('Total (words are in between)', 6)]

l2 = [('Total Amount', ['593.52']), ('Total (words are in between)', ['593.52'])]

The keys Total Amount and Total (words are in between) in l2 are to be matched from l1 and the value corresponding to keys present in l1 9 and 6 respectively in this case are to be added to either l2 or a new list.

Expected output:

l2 = [('Total Amount', ['593.52'],[9]), ('Total (words are in between)', ['593.52'],[6])]

I'll be happy to provide further clarification and I am unable to think about this would happen and I am sorry if this seems too messy and I looked for similar questions but nothing seemed apt Thank you!

question from:https://stackoverflow.com/questions/65914028/find-common-values-from-2-list-of-tuples-and-add-the-values-from-one-tuple-to-an

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

1 Reply

0 votes
by (71.8m points)

For readability I would create a temporarily dictionary of the l1 to easier do the look-up on the keys.

Unpack the tuples in l2 and compare the keys with those in the l1-dictionary. Create a new tuple if match and wrap everything in a list

l1_map = {k: v for k, v in l1}
l2_updated = [(key, num, [l1_map[key]]) for key, num in l2 if key in l1_map]

Result:

[('Total Amount', ['593.52'], [9]),
 ('Total (words are in between)', ['593.52'], [6])]

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

...