簡體   English   中英

在python中查找2D數組中的數字對的頻率

[英]Find frequency of pair of numbers in 2D array in python

我想在2D數組中找到對的頻率。 樣本輸入如下:

list_of_items = [[12,14,18],[12,19,54,89,105],[ 14, 19],[54, 88 ,105,178]]

預期產出如下:

(12,14):1
(12,18):1
(12,19):1
(12,54):1
(12,88):0
.
.
.
(54,105):2
.
.

我嘗試過以下代碼,但我認為這不是最佳解決方案:

number_set = [ 12, 14, 18,19,54,88,89 , 105, 178]

def get_frequency_of_pairs(list_of_items, number_set):
    x=1
    combination_list = []
    result = {}
    for i in number_set:
       for j in range(x,len(number_set)):
           combination_list = combination_list +[(i,number_set[j])]
       x = x+1
    for t in combination_list:
        result[t]=0
    for t in combination_list:
       for items in list_of_items:
           if( set(t).issubset(items) ):
              result[t]=result[t]+1
    return result

您可以使用itertools中的組合並使用集合中的Counter,如下所示:

counts = collections.Counter()
list_of_items = [[12,14,18], [12,19,54,89,105], [14,19], [54,88,105,178]]
for sublist in list_of_items:
    counts.update(itertools.combinations(sublist, 2))

print counts
Counter({(54, 105): 2, (88, 105): 1, (54, 89): 1, (19, 105): 1, (12, 14): 1, (14, 19): 1, (14, 18): 1, (12, 89): 1, (12, 19): 1, (89, 105): 1, (12, 18): 1, (19, 89): 1, (19, 54): 1, (105, 178): 1, (88, 178): 1, (54, 178): 1, (12, 105): 1, (12, 54): 1, (54, 88): 1})

必須枚舉每一對以進行計數,並且此方法使您只能枚舉每對。 應該是最好的時間復雜性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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