简体   繁体   中英

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

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

The expected output is:

[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

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:

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:

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. In the test run it gave:

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

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