python - 我如何创建类似于 "set intersection"的东西,允许一个项目从单个集合中丢失 n/1 次或更多次?

标签 python list python-2.7 set set-intersection

我想创建一个字符串列表:

a) 是 2 个或更多列表(出现在所有列表中的字符串)的交互,例如:

words = [["a", "b", "c"], ["d", "a", "b"], ["f", "a", "g"]]
set.intersection(*(set(t) for t in words))

返回:

set(['a'])

b) 是 2 个或多个列表的交集,除了单个字符串可能从单个集合中丢失 n 次,或者换句话说,字符串可以从 1 个或多个列表中丢失,因为我认为有必要。

假设我想允许它从单个列表中丢失,将该逻辑应用于我应该得到的上述单词变量:

set(['a', 'b'])

如果我允许它从 2 个集合中丢失,它将返回上述 words 变量中的所有字符。

我已经设法做到了a),但我如何才能做到b)呢?

最佳答案

使用 Counter计算每个单词出现的次数并选择出现次数最多的单词:

import collections
import itertools
counts = collections.Counter(itertools.chain.from_iterable(words))

threshold = len(words) - allowed_number_of_times_missing
results = {word for word in counts if counts[word] >= threshold}

如果单词可以在列表中重复出现,您可能希望将单个列表变成集合,这样您就不会多算:

counts = collections.Counter(itertools.chain.from_iterable(set(l) for l in words))

关于python - 我如何创建类似于 "set intersection"的东西,允许一个项目从单个集合中丢失 n/1 次或更多次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24091396/

相关文章:

python - 如何让python将 "YYYY W##"识别为日期时间对象,然后填充添加小于某一周的时间对象

带有参数和访问类实例的 Python 装饰器

使用 Fortran 的 Python 模块 : LNK1112 `module machine type ' X8 6' conflicts with target machine type ' x6 4'`

python - 在 Python 中将字节转换为有符号数

python - 使用 Flask SQLAlchemy SELECT DISTINCT YEAR()

python - 想要使用 python swiftclient 将 sqlite.db 文件上传到 swift 容器并且总是得到 utf-8 错误

list - Haskell 在最后一次出现时拆分字符串

python - 我收到一个我不明白的 ValueError

java - 如何随机排列图像列表?

python - 在 Python 2 中动态向迭代器添加属性