简体   繁体   中英

Comparing two lists of tuples and finding the frequency of the common elements

I have two lists of tuples:

myList1=[(1,2,3,4),(5,6,7),(8,9,10,11,12)]
myList2=[(1,2,7,6,2,1,3),(5,3,2,1,8,9,6),(11,12,1,2,5,6,6)]

I want to find the frequency of the elements in myList2 , which are common to myList1 and add them.

Something like this:

5

3

2

2

2

3

0

2

2

Explanation: 5 # In myList2 , elements of myList1 occurred 5 times. ie 1 (2 times), 2 (2 times) and 3 (1 time) , hence 5. Same applies for other results. I tried looping over two lists and using count , but it didn't work.

myList1=[(1,2,3,4),(5,6,7),(8,9,10,11,12)]

myList2=[(1,2,7,6,2,1,3),(5,3,2,1,8,9,6),(11,12,1,2,5,6,6)]

count = 0

for el in zip(myList1,myList2):

    for t in el[1]:
        if t in el[0]:
            count += 1
    print(el)
    print(count)
    count = 0

Output:

((1, 2, 3, 4), (1, 2, 7, 6, 2, 1, 3))

5

((5, 6, 7), (5, 3, 2, 1, 8, 9, 6))

2

((8, 9, 10, 11, 12), (11, 12, 1, 2, 5, 6, 6))

2

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