Comparing lists with their indices and content in Python

ccc

I have a list of numbers as

N = [13, 14, 15, 25, 27, 31, 35, 36, 43]

After some calculations, for each element in N, I get the following list as the answers.

ndlist = [4, 30, 0, 42, 48, 4, 3, 42, 3]

That is, for the first index in N (which is 13), my answer is 4 in ndlist.

For some indices in N, I get the same answer in ndlist. For example, when N= 13 and 31, the answer is 4 in ndlist.

I need to find the numbers in N (13 and 31 in my example) such that they have the same answer in ndlist.

Can someone help me to that?

Stephen Rauch

You can use a defaultdict and put those into a list keyed by the answer like:

Code:

N = [13, 14, 15, 25, 27, 31, 35, 36, 43]
ndlist = [4, 30, 0, 42, 48, 4, 3, 42, 3]

from collections import defaultdict
answers = defaultdict(list)
for n, answer in zip(N, ndlist):
    answers[answer].append(n)

print(answers)
print([v for v in answers.values() if len(v) > 1])

Results:

defaultdict(<class 'list'>, {4: [13, 31], 30: [14], 
            0: [15], 42: [25, 36], 48: [27], 3: [35, 43]})

[[13, 31], [25, 36], [35, 43]]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related