简体   繁体   English

查找具有共同价值观的列表

[英]Find the lists that share common values

My question is closely related to the following topic .我的问题与以下主题密切相关。 I have a number of lists and I want to find the lists that share common values.我有许多列表,我想找到具有共同价值的列表。 All lists have the same size.所有列表的大小相同。 The total number of lists is variable and can increase.列表的总数是可变的并且可以增加。 Minimum number of lists is 2最少列表数为2

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]

The expected output is:预期的 output 为:

[a, c]

Ideally, I also want the fastest method.理想情况下,我也想要最快的方法。 Thanks in advance,提前致谢,

You could cast them to sets and use the intersection() function, if it does return a value, there are some values in common您可以将它们转换为集合并使用intersection() function,如果它确实返回一个值,则有一些共同的值

lists = []
for i in a:
    if i in b:
        lists.append([a, b])
    if i in c:
        lists.append([a, c])
for i in b:
    if i in c:
        lists.append([b, c])
print(lists)

To simply check if two lists share at least one value you can use...要简单地检查两个列表是否共享至少一个值,您可以使用...

a = [1, 2, 3, 4]
b = [9, 10, 11, 1]

if any(a) == any(b):
    print(True)

If you want the ['a', 'c'] output for n named lists, you could save them in a dict and use any to check if they intersect while looping through them:如果您想要 n 个命名列表的['a', 'c'] output ,您可以将它们保存在dict中并使用any在循环它们时检查它们是否相交:

lists = {
    "a" : [1, 2, 3, 4],
    "b" : [5, 6, 7, 8],
    "c" : [9, 10, 11, 1]
}
res = []
for l in lists: 
    for l2 in lists: 
        if l is not l2: 
            if any(i in lists[l] for i in lists[l2]):
                res.append(l)
                break;
print(res)

OUT: ['a', 'c']

Using my limited knowledge on Python lists, I came up with this:利用我对 Python 列表的有限知识,我想出了这个:

class countedList:
    def __init__(self,listt):
        self.listt = listt
        self.sharedNum = 0

def mostCommon(*lists):
    for item in lists:
        for listItem in item.listt:
            for item2 in lists:
                item2.sharedNum+=item2.listt.count(listItem)
                
    new = sorted(lists,key=lambda clist: clist.sharedNum,reverse=True)
    return new[:2]

test = mostCommon(countedList([1, 2, 3, 4]),countedList([5, 6, 7, 8]),countedList([9, 10, 11, 1]))

Well yeah, I had to make up a custom class for it.嗯,是的,我必须为它制作一个定制的 class。 In the test run it gave:在测试运行中它给出了:

>>> test[0].listt
[1, 2, 3, 4]
>>> test[1].listt
[9, 10, 11, 1]

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

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