python - 计算数组中的列表成员对
问题描述
假设,我有一个包含以下列表的数组:
data = [['a', 'b', 'c'],['a', 'b'],['c']]
按它们所在的列表数量计算每一对出现的最佳解决方案是什么?
例如结果应该是:
member_one_is member_two_is COUNT
a b 2
a c 1
b c 1
解决方案
一种使用collections.Counter
and的方法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
。
推荐阅读
- java - 如何修复“ java.lang.UnsatisfiedLinkError: no opencv_java320 in java.library.path:
- three.js - 如何在 Three.JS 中去除模型的光泽
- javascript - 条纹国家下拉菜单被切断
- python - 在目录中的哪里可以找到文件?
- xml - 如何将文本部分提取到基于 id 命名的单独文件中?
- python - Python 数据框 sume 迭代
- jquery - 如何从单独的函数调用 dropzone processQueue()?
- android - 如何触摸画布点中的特定项目
- java - 当我单击选项菜单时,折叠工具栏上的滚动错误
- python - 如何找到当前 spark 上下文中加载的所有 textFile(s)?