Python list comparison

im trying to compare one list with three other lists with the same number of indices. for example i have this list

[A, B, C] 

and I created with a certain function another list with random nested lists for example:

  [[A ,B ,B], [C, B, A], [B, B, C]] 

but I want to compare each nested list with the original list and see how many characters in each nested list are in the same place as in the original list. It works when I compare each index in the original list with each of the three indexes in the nested list. My teacher says this is good, but it looks silly to me, what if I had 100 nested lists? There must be a better way to compare listings. anybody suggestions?

+2
source share
1 answer

You can do it as follows:

 from itertools import izip def matches(input_lists, base_list): for l in input_lists: yield sum(1 for a, b in izip(l, base_list) if a==b) 

and the result will be as follows:

 >>> for i in matches([[1,2,3],[2,3,1],[0,2,0]], [1,2,4]): i 2 0 1 

which works as expected.

The izip() function is a generator function, which is a better solution than zip() . Also, matches() we defined the generator function, so there should be less problems when processing large lists.

Did it help? Is it clean enough?

+1
source

Source: https://habr.com/ru/post/901848/


All Articles