Home > other >  Why listay is not appending the elements?
Why listay is not appending the elements?

Time:09-15

I'm very new in Python and coding in general, so this question probably will sound dumb. I want to append tuples with two elements in listay: if the first element of l2 matches with any first element of listax, then it would be appended as a tuple in listay with its second element.

If it worked my output (print(listay)) would be: ['a',4),('b',2), ('c',1)]. Instead, the output is an empty list. What am I doing wrong?

Also, I am sorry if I am not offering all the information necessary. This is my first question ever about coding in a forum.

import operator


listax= []

listay= []

l1= [('a',3), ('b',3), ('c',3), ('d',2)]

l2= [('a',4),('b',2), ('c',1), ('d',2)]

sl1= sorted(l1, key= lambda t: t[1])

sl2= sorted(l2, key= lambda t: t[1])



tup1l1= sl1[len(sl1)-1]

k1l1= tup1l1[0]

v1l1= tup1l1[1]



tup2l1= sl1[len(sl1)-2]

k2l1= tup2l1[0]

v2l1= tup2l1[1]




tup3l1= sl1[len(sl1)-3]

k3l1= tup3l1[0]

v3l1= tup3l1[1]




tup1l2= sl2[len(sl2)-1]

k1l2= tup1l2[0]

v1l2= tup1l2[1]



tup2l2= sl2[len(sl2)-2]

k2l2= tup2l2[0]

v2l2= tup2l2[1]



tup3l2= sl2[len(sl2)-3]

k3l2= tup3l2[0]

v3l2= tup3l2[1]



listax.append((k2l1, v2l1))

if v2l1== v1l1:
    listax.append((k1l1, v1l1))
if v2l1== v3l1:
    listax.append((k3l1, v3l1))
    


for i,n in l2:
    if i in listax:
        listay.append((i,n))
    print(listay)

CodePudding user response:

I'll play the debugger role here, because I'm not sure what are you trying to achieve, but you could do it yourself - try out breakpoint() build-in function and python debugger commands - it helps immensely ;)

Side note - I'm not sure why you import operator, but I assume it's not related to question.

You sort lists by the second element, ascending, python sort is stable, so you get:

sl1 = [('d', 2), ('a', 3), ('b', 3), ('c', 3)]
sl2 = [('c', 1), ('b', 2), ('d', 2), ('a', 4)]


k1l1 = 'c'
v1l1 = 3

k2l1 = 'b'
v2k1 = 3

k3l1 = 'a'
v3l1 = 3


k1l2 = 'a'
v1l2 = 4

k2l2 = 'd'
v2k2 = 2

k3l2 = 'b'
v3l2 = 2

after append

listax = [('b', 3)]

v2l1 == v1l1 is True 3 == 3, so

listax = [('b', 3),  ('c', 3)]

v2l1 == v3l1 is True 3 == 3, so

listax = [('b', 3), ('c', 3), ('a', 3)]

I think it gets tricky here:

for i,n in l2:

with

l2 = [('a', 4), ('b', 2), ('c', 1), ('d', 2)]

we get

i = 'a'
n = 4

maybe you wanted enumerate(l2)?

'a' in listax ([('b', 3), ('c', 3), ('a', 3)]) is False listax doesn't contain an element equal to 'a' - it contains an element, which contains the element 'a'. Maybe that's the mistake?

i = 'b'
n = 3

just like before

nothing interesting happens later ;)

Hope this helps :D

  • Related