简体   繁体   English

在python中找到匹配索引组

[英]find match index group in python

What the simplest wayto determine which index group is searched in python 确定在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? 我们想知道哪个索引组匹配A,B或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 . 您的示例是,如果input[Yes, No, Yes] ,则应匹配C ,即C 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 . 因此,大概您想知道input是否具有与ABC相同的元素(以任何顺序)。

One way to do this is by using collections.Counter as a multiset: 一种方法是使用collections.Counter作为多集:

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. ABC之间的差异只是每个Yes值有多少。 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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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