2020年3月11日 星期三

[ Python 常見問題 ] Counting “unique pairs” of numbers into a python dictionary?

Source From Here
Question
If I have a list of tuple as below:
  1. datas = [(1, 2), (1, 2, 3), (2, 3, 4)]  
How to count pair of number such as:
(1, 2) = (1, 2)
(1, 2, 3) = (1, 2), (1, 3), (2, 3)
(2, 3, 4) = (2, 3), (3, 4), (2, 4)

Then we got: {(1, 2): 2, (1, 3): 1, (2, 3): 2, (3, 4): 1, (2, 4): 1}

How-To
What you want is to count pairs that arise from combinations in your lists. You can find those with a Counter and combinations.
  1. from itertools import combinations  
  2. from collections import Counter  
  3.   
  4. datas = [(1, 2), (1, 2, 3), (2, 3, 4)]  
  5. counter = Counter()  
  6.   
  7. for t in datas:  
  8.     counter.update(Counter(combinations(t, 2)))  
  9.       
  10. display(counter)  
Output:
Counter({(1, 2): 2, (1, 3): 1, (2, 3): 2, (2, 4): 1, (3, 4): 1})


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...