首页 > 解决方案 > 计算数组中的列表成员对

问题描述

假设,我有一个包含以下列表的数组:

data = [['a', 'b', 'c'],['a', 'b'],['c']]

按它们所在的列表数量计算每一对出现的最佳解决方案是什么?

例如结果应该是:

member_one_is  member_two_is  COUNT
a              b              2
a              c              1
b              c              1

标签: pythonpandasdataframe

解决方案


一种使用collections.Counterand的方法itertools.combinations

from collections import Counter
from itertools import combinations

import pandas as pd

data = [['a', 'b', 'c'], ['a', 'b'], ['c']]

# get the counts using collections Counter and the combinations using combinations
# make sure each sub-list is sorted with sorted
counts = Counter(combination for lst in map(sorted, data) for combination in combinations(lst, 2))

# create the DataFrame
df = pd.DataFrame(data=[[*k, v] for k, v in counts.items()], columns=["member_one_is", "member_two_is", "COUNT"])
print(df)

输出

  member_one_is member_two_is  COUNT
0             a             b      2
1             a             c      1
2             b             c      1

请注意,如果列表已排序,您可以跳过map(sorted, data)并直接遍历data


推荐阅读