簡體   English   中英

如何計算嵌套列表中多個交叉點的出現次數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM