2

im trying to compare between one list and 3 other lists with the same number of indexes. for example I have this list

 [A, B, C]

and I have created with a certain function another list with random nested lists such as:

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

but I want to compare each nested list to the original list and see how many characters in each nested list is in the same place as in the original list It works when I compare each index in the original list to each of three indexes in the nested list. My teacher says its fine, but to me it looks stupid, what if i had 100 nested lists? there must be a better way to compare between lists. suggestions anyone?

2
  • Well, it will obviously take longer if you have more lists to check. But that seems to be unavoidable - if order (indices) really matter, I don't see any way to speed it up significantly (for instance, sets are out of question)... Commented Nov 18, 2011 at 15:30
  • two loops seem fine to me regardless of the number of nested lists. Commented Nov 18, 2011 at 15:31

1 Answer 1

1

You can do it like this:

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 following:

>>> 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 generator function, which is better solution than zip(). Also matches() we defined is generator function, so there should be less problems when processing large lists.

Did it help? Is it clean enough?

Sign up to request clarification or add additional context in comments.

3 Comments

I think that you could replace that sum with an all(). See also any().
Moreover, you should drop the square brackets. There's no point in having a list comprehension, just make it a generator expression.
@delnan: I agree, I have updated it to generator expression. @Kos: I do not follow, how would you use all() in this case? As far as I understand, the number of matching elements should be returned, not whether all of them are matched.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.