如何在具有条件的列表中查找匹配项



给定数据集:

P = {"alice": "R", "bob": "D", "carol": "D"}
V = {"alice": [True, True, False, True, None],
"bob": [True, False, None, True, True],
"carol": [False, False, False, None, None]}

我想得到以下结果:

#[('alice', 'bob', 2), ('alice', 'carol', 1)]

我们需要比较"R"one_answers";D">

result = [['alice','bob',0],['alice','carol',0]]
for alice, bob, carol in zip(V.alice,V.bob,V.carol):
if alice == bob:
result[0][2] = result[0][2] + 1
if alice == carol:
result[1][2] = result[1][2] + 1

有很多方法可以做到这一点。这是我使用的方法,
首先,您需要反转p,因为我认为这是最简单的方法。我使用了下面的代码:

p_r = {}
for a, b in p.items():
if p_r.get(b):
p_r[b] += [a]
else:
p_r[b] = [a]

然后像往常一样开始比较:

k = []
for i in p_r['R']:
for j in p_r['D']:
s = [x == y and x is not None for x, y in zip(v[i], v[j])]
k.append((i, j, s.count(True)))

最终代码:

p = {"alice": "R", "bob": "D", "carol": "D"}
v = {"alice": [True, True, False, True, None],
"bob": [True, False, None, True, True],
"carol": [False, False, False, None, None]}
#  reverse dict p
p_r = {}
for a, b in p.items():
if p_r.get(b):
p_r[b] += [a]
else:
p_r[b] = [a]

k = []
for i in p_r['R']:
for j in p_r['D']:
s = [x == y and x is not None for x, y in zip(v[i], v[j])]
k.append((i, j, s.count(True)))

print(k)

首先使用列表推导法提取RD的名称列表

>>> [k for k,v in P.items() if v=='D']
['bob', 'carol']
>>>[k for k,v in P.items() if v=='R']
['alice']

然后使用itertools.product

从这些列表中找到组合
>>>import itertools
>>>list(itertools.product([k for k,v in P.items() if v=='D'],[k for k,v in P.items() if v=='R']))
[('bob', 'alice'), ('carol', 'alice')]

从字典V中为每个组合提取布尔值列表

>>>first_comb = ('bob', 'alice')
>>>[V.get(person) for person in first_comb]
[[True, False, None, True, True], [True, True, False, True, None]]

获取list

之间的逻辑与(使用all())结果的和。
>>>sum([all(elem) for elem in zip(*[V.get(person) for person in first_comb])])
2

把所有

import itertools
P = {"alice": "R", "bob": "D", "carol": "D"}
V = {"alice": [True, True, False, True, None],
"bob": [True, False, None, True, True],
"carol": [False, False, False, None, None]}
combinations = list(itertools.product([k for k,v in P.items() if v=='D'],[k for k,v in P.items() if v=='R']))
output = [(*item,sum([all(elem) for elem in zip(*[V.get(person) for person in item])])) for item in combinations]
print(output)

o/p: -

[('bob', 'alice', 2), ('carol', 'alice', 0)]

相关内容

  • 没有找到相关文章

最新更新