我想创建一个字符串列表:
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/