简体   繁体   中英

find match index group in python

What the simplest wayto determine which index group is searched in python

example:

desire value

Yes, Yes, No

value provided

A = No, No, No
B = Yes, No, No
C = Yes, Yes, No

We want to know which index group matches A, B, or C?

I'm going to take a wild leap into the dark here and guess what you're trying to do. If I've guessed wrong, this answer will be useless, and I'll delete it.

Your example is that if input is [Yes, No, Yes] , it should match C , which is Yes, Yes, No . So presumably you want to know if input has the same elements—in any order—as any of A , B , and C .

One way to do this is by using collections.Counter as a multiset:

from collections import Counter

A = Counter(('No', 'No', 'No'))
B = Counter(('Yes', 'No', 'No'))
C = Counter(('Yes', 'Yes', 'No'))

input = ['Yes', 'No', 'Yes']
input_multiset = Counter(input)

if input == A:
    print('A')
elif input == B:
    print('B')
elif input == C:
    print('C')
else:
    print('no match')

Now, there are ways you could simplify and/or optimize this, but the best way is to rethink the problem. The difference between A , B , and C is just how many Yes values each has. So:

from collections import Counter

abc = {0: 'A', 1: 'B', 2: 'C']

input = ['Yes', 'No', 'Yes']
input_counts = Counter(input)
yes_count = input_counts['Yes']
print(abc.get(yes_count, 'no match'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM