Home > OS >  Checking if two elements match in a nested list (python)
Checking if two elements match in a nested list (python)

Time:12-24

I have a list of the format:

my_list= [['ezis', 0], ['camera', 15], ['size', 0], ['esu', 16], ['take', 4],
 ['pictur', 26], ['tnaw', 46], ['thing', 49], ['ilno', 8],.....]

and I would like to see if the number at the end matches the reverse of the string (for example, in this list ['ezis', 0] and ['size', 0] would match with one another as they both have 0 as its end value and 'size' reversed is 'ezis'. I would then like to keep a count of the number of these matches.

So far I have:

matches = 0

for x,y in my_list:
    if (x[0]==y[0][::-1]) and x[1]==y[1]:
        matches =1    #a match is found

But I am getting an error and am not sure how else to approach this

Could anyone help?

CodePudding user response:

Try:

>>> sum(1 for k, v in dict(my_list).items() if v==dict(my_list).get(k[::-1]))
2

CodePudding user response:

If you want to count size and ezis as 1, you can do:

d = {}
for x,y in my_list:
    d.setdefault(y, set()).add(x)
    
matches = 0
for k,v in d.items():
    x = v.pop()
    if x[::-1] in v:
        matches  = 1
  • Related