[英]How can I count the number of occurrences of multiple intersections in a nested list
更新的问题:我有许多与此类似的嵌套列表:
l = [['y', 'ha', 'ua', 'uk'], ['o', 'j', 'sb', 'ku'],
['j', 'c', 'ts', 'ar'], ['nec', 'hv', 'f', 'uf'],
['y', 'nec', 'fs', 'ks']]
每个列表是一组人,每个子列表是一个人的特征。 我想计算具有重叠特征的人数。
我创建了一个计数器字典来查找所有 > 1 的结果。
dups = dict((k, v) for k, v in dups.items() if (v >= 2))
#{'y': 2, 'j': 2, 'nec': 2}
如果我将 dups 的值加在一起,当只有 5 个子列表时,我会得到 6。 我需要找到具有多个重叠值的所有子列表。
换句话说,我的问题是我怎样才能得到 5(因为所有 5 个子列表至少有 1 个共同的值)。
我尝试创建组合如下:
import itertools
characteristics = list(dups.keys())
set_c = set(characteristics)
combos = list(itertools.combinations(set_c, 2))
sub_list = list(combos)
sub_list2 = [list(x) for x in sub_list]
print(sub_list2)
#[['nec', 'y'], ['nec', 'j'], ['y', 'j']]
我尝试了下面的代码,但它有问题(比如它不计算多个布尔值):
counter = 0
if (all(x for y in l for x in sub_list2)):
counter += 1
print(counter)
else:
print("No, list is not subset of other.")
有什么想法吗?
我不清楚要求,但这可能是您要找的:
l = [['y', 'ha', 'ua', 'uk'],
['o', 'j', 'sb', 'ku'],
['j', 'c', 'ts', 'ar'],
['nec', 'hv', 'f', 'uf'],
['y', 'nec', 'fs', 'ks']]
# get all keys
all = set()
for l2 in l:
all |= set(l2) # merge elements, remove duplicates
d = {k:0 for k in all} # dictionary for counts
for l1 in l:
for e in l1:
d[e] += 1
t = [(k,d[k]) for k in d if d[k] > 1] # remove count = 1
print(t)
输出
[('j', 2), ('nec', 2), ('y', 2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.