Python:计算列表列表中的元素对的频率 [英] Python: Counting frequency of pairs of elements in a list of lists
问题描述
其实,我有一个关于会议的数据集。
例如,A,B,C有一个会议,那么列表将是[A,B,C]。
像这样,每个列表将包含参加会议的成员的列表。
因此:
line1 =(A,B,C)
line2 = C,D,E)
line3 =(D,F,G)
...
我只想计算每对会员相遇的次数。
例如,成员A从line1和line2两次遇到C两次,并且成员B从line1一次遇到C次。所以,我想制作一个这样的图表。
ABCDEF G ...
一个 。 1 2 1 ...
B 1。 1 0
C
...
我以为这很容易在第一次,但我很困惑。
请帮助我,提前多谢。
=http://docs.python.org/library/collections.html#collections.counter =noreferrer> collections.counter
itertools
:
from collections import Counter
来自itertools导入链,组合
meets = Counter(chain.from_iterable )
其中 lines
是可迭代的名称的迭代。
Actually, I have a dataset about a "meeting". For example, A,B,C have a meeting, then the list would be [A,B,C]. Like this, each list would contain a list of members who participated in the meeting. Therefore:
line1= (A,B,C)
line2= (A,C,D,E)
line3 = (D,F,G)
...
I just would like to count the number how many times each pair of members meet each other. For example, member A meets C two times from line1 and line2 and member B meets C one time from line1. So, I would like to make a chart like this..
A B C D E F G...
A . 1 2 1 ...
B 1 . 1 0
C
...
I thought it would be easy at the first but I am pretty confused. Please help me and thank you so much in advance.
Rather than manually summing frequencies, use collections.counter
along with itertools
:
from collections import Counter
from itertools import chain, combinations
meets = Counter(chain.from_iterable(combinations(line, 2) for line in lines))
Where lines
is an iterable of iterables of names.
这篇关于Python:计算列表列表中的元素对的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!