Python: frequency of counting pairs of items in a list of lists

Actually, I have a data set about the “meeting”. For example, A, B, C have a meeting, then the list will be [A, B, C]. Thus, each list will contain a list of participants who participated in the meeting. Therefore:

line1 = (A, B, C)

line2 = (A, C, D, E)

line3 = (D, F, G)

...

I just wanted to calculate how many times each pair of members meets each other. For example, member A meets C twice from row1 and row2, and member B meets C once from row1. So, I would like to make such a schedule.

    A  B  C  D E F G...

 A  .  1  2  1 ...  

 B  1  . 1  0 

 C

...

I thought it would be easy the first time, but I'm pretty confused. Please help me and thank you for this in advance.

+5
source share
3 answers

, , collections.counter itertools:

from collections import Counter
from itertools import chain, combinations

meets = Counter(chain.from_iterable(combinations(line, 2) for line in lines))

lines - .

+7

2D- dict. , , , .

times_met = defaultdict(int)
for line in lines:
     for pair in itertools.combinations(line, 2)
         times_met[pair] += 1

# How many times person a meets person b is described by the following (s.t. a < b)
print times_met[(a, b)]

, , , , .

0

It looks like you should solve this problem by adding a matrix. If you know the total number of people (G in the question), then your answer will be a GxG matrix. Create a GxG matrix with combinations from row 1, then add a GxG matrix with combinations from row2, etc.

0
source

All Articles