Comparison of 2d lists

Hello!

I have two 2d lists:

lst1 = [[1,'abc'],
        [2,'abcv'],
        [3,'rfre'],
        [4,'tggr'],
        [5,'tftg']]

lst2 = [[1,'abc'],
        [2,'abcv'],
        [5,'tftg']]

What I want to do is compare them both at [i][0], and if it is the same e.g both lists have 1 at [0][0], I would like to append only the [i][1] of list2(shorter list) to a new list called main list. Else append ‘-1’ because I’d like to keep the length of list1 since its a comparison.

The code I have so far:

mainlst = [i[1][1] if i[0][0]==i[1][0] else -1 for i in zip(lst1,lst2)]

print(mainlst)

The output I’m having:

['abc', 'abcv', -1]

But the output I want is:

['abc', 'abcv', -1,-1, 'tftg']

Thank you for your reply. Your point about index makes sense to me and i understand why it didnt provide the output i wanted. And your assumption about what I’m trying to do is absolutely correct. What should I do instead?

And yes lst2 will always be the shorter one.

That’s because zip() only takes the length of the shortest element.
You either have to make the second list longer to match the first - or use another method entirely.

Plus you approach cannot work given you want to match the [5,'tftg'] element. But how? How is Python supposed to know this element on index 2 in one list is supposed to be compared to another element on index 4?

You only compare items with the same index. But you want to compare items based on the first entry in the nested lists. You’d basically have to search through the entire second list for every item in the first list, in order to find a potential match. This cannot be done with zip().

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.