简体   繁体   中英

Python - Find a tuple in list of lists

I have list of tuples ( mytuples ) and a list of lists ( mylist ).

I want to find how many times each tuple in mytuples occurs in every list.

Say tuple (2,3) occurs in [1,2,3,4] , [2,3,4,5] and [2,3] . Therefore count of (2,3) is 3 .

Tuple and list size can be different.

mytuples = [(2,3), (3,6), (1,2)]
mylist = [[1,2,3,4],[2,3,4,5],[2,3],[4,5,6]]

count={}    
for m in mytuples :
    counter = 0        
    for i in mylist :
        if set(m).issubset(i):
            counter = counter + 1
    count[m]=counter

My output would be {(2,3):3, (3,6): 0, (1,2):1}

This approach works fine but when my list size is huge say 1000 of records, it is more time consuming. Can this be done faster? any suggestions?

Using dict comprehension we could reduce everything to one single-line.

And assuming the tuples are always pairs:

count = {(x,y):sum((x in i and y in i) for i in mylist) for x,y in mytuples}
# {(1, 2): 1, (2, 3): 3, (3, 6): 0}

Or you could sum using all() if tuple size is unkown:

count = {t:sum(all(x in i for x in t) for i in mylist) for t in mytuples}
# {(1, 2): 1, (2, 3): 3, (3, 6): 0}

If this isn't clear:

We go through multiple of these:

[all(x in i for x in (2,3)) for i in mylist]
# [True, True, True, False] 
# sum([True, True, True, False]) = 3
# And we assign them back to the tuple

Your current algorithm can be made somewhat faster with a small adjustment:

# Your input data.
tuples = [(2,3), (3,6), (1,2)]
lists = [[1,2,3,4],[2,3,4,5],[2,3],[4,5,6]]

# Convert to sets just once, rather than repeatedly
# within the nested for-loops.
subsets = {t : set(t) for t in tuples}
mainsets = [set(xs) for xs in lists]

# Same as your algorithm, but written differently.
tallies = {
    tup : sum(s.issubset(m) for m in mainsets)
    for tup, s in subsets.items()
}

print(tallies)

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