实际上,我有一个关于"会议"的数据集.例如,A,B,C有会议,那么列表将是[A,B,C].像这样,每个列表都包含参加会议的成员列表.因此:
line1 =(A,B,C)
line2 =(A,C,D,E)
line3 =(D,F,G)
...
我只想计算每对成员相遇的次数.例如,成员A从line1和line2遇到C两次,成员B从line1遇到C一次.所以,我想制作一个这样的图表..
A B C D E F G...
A . 1 2 1 ...
B 1 . 1 0
C
Run Code Online (Sandbox Code Playgroud)
...
我觉得一开始会很容易,但我很困惑.请帮助我,并提前感谢你.
而不是手动求和的频率,使用collections.counter连同itertools:
from collections import Counter
from itertools import chain, combinations
meets = Counter(chain.from_iterable(combinations(line, 2) for line in lines))
Run Code Online (Sandbox Code Playgroud)
lines可迭代的名称迭代在哪里.
这是一个非常简单的二维数组或字典的数据结构问题。如果你有很多人,数组会更有效,但我假设你没有。
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)]
Run Code Online (Sandbox Code Playgroud)
请注意,如果您有大型会议并且可能存在更高效的算法,那么这确实效率很低。