Python 列表中列表成对比较中元素的频率

Frequency of elements in pairwise comparison of lists within a list in Python

我有一个这样的列表列表:

my_list_of_lists = 
[['sparrow','sparrow','sparrow','junco','jay','robin'],
['sparrow','sparrow','junco', 'sparrow','robin','robin'],
['sparrow','sparrow','sparrow','sparrow','jay','robin']]

我想对所有列表的每个位置进行成对比较,列表如下:

#1 with 2
['sparrow','sparrow','sparrow','junco','jay','robin']
['sparrow','sparrow','junco', 'sparrow','robin','robin']

#1 with 3
['sparrow','sparrow','sparrow','junco','jay','robin']
['sparrow','sparrow','sparrow','sparrow','jay','robin']

#2 with 3
['sparrow','sparrow','junco', 'sparrow','robin','robin']
['sparrow','sparrow','sparrow','sparrow','jay','robin']

所以 1 和 2 的配对:

pairs =[('sparrow','sparrow'), ('sparrow','sparrow'), ('sparrow','junco'),('junco','sparrow'),('junco','junco'), ('jay','robin'), ('robin','robin')]

我想在每个成对比较中获得成对的计数和频率:

pairs =[('sparrow','sparrow'), ('sparrow','sparrow'), ('sparrow','junco'),('junco','sparrow') ('junco','junco'), ('jay','robin'), ('robin','robin')]

sparrowsparrow_counts = 2
juncosparrow_counts = 2
jayrobin_counts = 1
robinrobin = 1

frequency_of_combos = [('sparrow', 'sparrow'):.333, ('sparrow', 'junco'):.333, ('jay', 'robin'):.167, ('robin', 'robin'): .167]

我试过压缩,但我最终将所有列表(不是成对的列表)压缩成元组,剩下的让我很困惑。

我认为它与 How to calculate counts and frequencies for pairs in list of lists? 有点相关,但我不知道如何将其应用于我的数据。

压缩两个列表,然后过滤掉不匹配的对,并使用collections.Counter统计它们:

from collections import Counter

a = ['sparrow','sparrow','sparrow','junco','jay','robin']
b = ['sparrow','sparrow','junco', 'sparrow','robin','robin']
c = Counter([ i for i in zip(a,b) if i[0] == i[1]])
print(c)


Counter({('sparrow', 'sparrow'): 2, ('robin', 'robin'): 1})

您似乎已经弄清楚了频率部分,但这应该清除 zip 和计数器的使用。