How to compare 2 lists and get only some specific values?

Question:

I have this problem that I can’t solve.
I don’t want to use numpy or other libraries, I just want to understand the logic but I can’t solve it.
So I have 2 lists:

t1 = [(2, 1), (5, 1), (7, 1)]
t2 = [(2, 3), (3, 1), (5, 1)]

And I want to get this:

lista = [(2, 1), (5, 1)]

I use this loop to select the values to put in the list:

counter = len(t1)
c = 0
print(t1[c][0])

lista = []
for e in range(counter):
    if t1[c][0] == t2[c][0]:
        lista.append(t1)
        c += 1
        
print(lista)   

As a result I get this thing:

[[(2, 1), (5, 1), (7, 1)]]
 

But I have tried them all (<, >, <=, >=, I think) and I can’t get the correct values selected.

In my opinion what this code should do is compare the values in t1[0][0], i.e. (2) with t2[0][0], i.e. (2). In theory if they are not equal it should not put anything in the list.
Okay for the first 2 and 2 is correct, but the second 5 and 3? and the third 7 and 5?
Why the hell does he add them?

Don’t suggest set(). I’m stubborn and would like to solve with lists and understand the logic.

Can someone let me know where I am going wrong. Thanks

Asked By: Prectux

||

Answers:

You appended the whole list to the new list, that’s why you get the wrong answer you want:

lista.append(t1)

This will append the whole list t1 to the new lista. Just change it to t1[c] then you will not get all the items.

However, this will still only compare item with same index, so it will still be wrong.
This is actually a search problem and you can search more online. Here is a simple solution to achieve what I believe you want.

t1 = [(2, 1), (5, 1), (7, 1)]
t2 = [(2, 3), (3, 1), (5, 1)]

lista = []
for i in range(len(t1)):
    j = 0
    while (j < len(t2)):
        if t1[i][0] == t2[j][0]:
            lista.append(t1[i])
            break
        j += 1
        
print(lista)   

PS: please explain your end goal and question clearly next time so we can look at it easier and answer faster. We don’t need to know your thought process if it doesn’t relate to the question.

Answered By: Ice
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.