TinaTz
TinaTz

Reputation: 311

Compare two lists of unequal length and non-matching elements

I have two lists of unequal length and non-matching values as shown below:

list_1 = [1,7,9]
list_2 = [0.1,0.2,0.3,0.8,0.11,0.12,0.13,0.14,0.19,0.009]

For each value in list_1 I want to extract its matching value in list_2. The result should be like this:

result[1:0.1,7:0.13,9:0.19]

Currently I have this:

find_minimum = min(len(list_1),len(list_2))
for i in range(find_minimum):
    print(list_1[i],list_2[i])

And this is the result:

1:0.1
2:0.2
3:0.3

Upvotes: 0

Views: 221

Answers (2)

John Kugelman
John Kugelman

Reputation: 361595

Instead of looking up the i-th index in list_2, you want to look up the list_1[i]-th index.

for i in range(find_minimum):
    print(list_1[i], list_2[list_1[i]])

If that's confusing to read, save list_1[i] in a temporary variable to make it easier to understand:

for i in range(find_minimum):
    index = list_1[i]
    print(index, list_2[index])

Upvotes: 0

tomjn
tomjn

Reputation: 5389

You should look up python dictionaries, which allow a key to value mapping. You should also know that python is zero indexed and so the first entry of list_1 is list_1[0].

With a dictionary you can write a solution like

result = dict() # a new dictionary, could also just write result = {}
for i in list_1:
    result[i] = list_2[i-1]
print(result)

will print

{1: 0.1, 7: 0.13, 9: 0.19}

You'll often see people use a dict comprehension for this which would look like

result = {i: list_2[i-1] for i in list_1}

Upvotes: 1

Related Questions