r4b1n r4b1n - 1 year ago 70
Python Question

how to match items between 2 different lists

I have 2 different lists:

['2', '1']
['equals', 'x']

I want to match the items so 2 = "equals" and 1 = "x" in order to recreate the original sentence "x equals x", also i have a third list which is:

['1', '2', '1']

I need the third list to recreate the original sentence since it has all the positions, to do this I thought of making the numbers equal to the words such as 1 = "x" and printing the list of numbers in order to have the full sentence. The problem is i do not know how to make the numbers equal to the words. Thanks for the help in advance

Answer Source

A dictionary might be what you need here which maps keys to values. You can create a dictionary from the first two lists by zipping them. And with this dictionary, it should be fairly straight forward to map any list of numbers to words:

mapping = dict(zip(['2', '1'], ['equals', 'x']))

# {'1': 'x', '2': 'equals'}

[mapping.get(num) for num in ['1', '2', '1']]
# ['x', 'equals', 'x']

To make the list a sentence, use join method:

" ".join(mapping.get(num) for num in ['1', '2', '1'])
# 'x equals x'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download