繁体   English   中英

匹配顺序无关紧要的集合中的确切元素

[英]Matching exact elements in a set where order doesn't matter

我是python新手,无论顺序如何,我都试图匹配两组之间的确切元素。 因此,如果我的2套是:

reflist = [1],[2,3,4],[5,6]
qlist = [1,2,3,4],[6,5]

比赛次数应为1,即5,6

我尝试编写以下循环以将qlist中的元素与reflist进行匹配,并计算匹配数:

i = 0
count = 0
for each in qlist:
    while i < len(qlist):
        if each.split(",").sort == reflist[i].split(",").sort:
            count = count + 1
        i = i + 1
print count

但是,即使qlist中的5和6的顺序是5,6,我也总是得到count = 0。 非常感谢您的帮助!

这可以做到:

如果没有重复项:

matches = [x for x in map(set, reflist) if x in map(set, qlist)]

如果重复:

matches = [x for x in map(sorted, reflist) if x in map(sorted, qlist)]

如果您的“集合”中没有重复项,请将“集合”转换为一组frozenset ,然后找到该集合的交集 -

i = set(map(frozenset, reflist))
j = map(frozenset, qlist)

len(i.intersection(j))
1

您可以始终为此使用collections.Counter()

from collections import Counter

reflist = [[1],[2,3,4],[5,6]]
qlist = [[1,2,3,4],[6,5]]

result = [list(x.keys()) for x in [Counter(y) for y in reflist] if x in [Counter(y) for y in qlist]]

print(result)

哪些输出:

[[5,6]]

这是我的一线书,使用了frozensetand

len(set(map(frozenset, qlist)) and set(map(frozenset, reflist)))

我了解您是Python的新手,因此我将使用您自己的方法回答您的问题,仅是为了记录基本的直接答案以供将来参考。

首先,您的代码根本不应该运行。 必须出错,因为eachreflist[i]都是列表,并且您正在对它们应用split(",")的字符串方法。 因此,您将获得count = 0的初始值。 您必须首先检查代码是否甚至触及了qlistreflist所有元素。 这不是Code Review ,因此我将它留给您来运行它并查看答案:

i = 0
count = 0
for each in qlist:
    while i < len(qlist):
        print i
        print each
        print reflist[i]
        i = i + 1

请记住: 您不必迭代索引! 您可以直接循环遍历可迭代元素! 这是您要寻找的答案:

match = [] # Optional, to see all the matching elements
count = 0 
for q in qlist:
    for r in reflist:
        if set(q) == set(r):
            print q, r
            match.append(q)
            count += 1 
print match
print count, len(match)

暂无
暂无

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

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