python 查找二维数组长度,在Python中查找二维数组中一对数字的频率

I want to find frequency of pairs in a 2D array.

Sample inputs is as follows:

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

Expected Output is as following:

(12,14):1

(12,18):1

(12,19):1

(12,54):1

(12,88):0

.

.

.

(54,105):2

.

.

I have tried following code but I think it is not optimal solution:

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

解决方案

You can use combinations from itertools and use a Counter from collections as follows:

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})

Each pair has to be enumerated to be counted, and this method enables you to enumerate each pair only once. Should be best possible time complexity.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值