Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

comparing lists python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...