-2
a = [1,2,3]
b = [2,3,4]
c = [1,2,4]
d = [1,3,6]

Hi, all,

I have the above lists, I'd like to show pairwise intersection/overlap (# of duplicated integers) of the each two lists like the following format. Any one knows how to achieve this? (any method would be great, but just curious is iterative/loop the only method to achieve this?)

   a  b  c  d
a  3  2  2  2
b  2  3  2  1
c  2  2  3  1
d  2  1  1  3

The true goal is more difficult for me, I need to sum up all duplicated number in each two list. For example, list a and list b are duplicated in number 2 and 3, thus I need 5 here. The ultimate goal is like below:

   a  b  c  d
a  6  5  3  4
b  5  9  6  3
c  3  6  7  1
d  4  3  1  10
4

3 回答 3

1

下面是一个对 numpy 数组 X 进行成对操作的实现。这种方法假设操作是对称的以提高速度。

from itertools import combinations_with_replacement
import numpy as np

def pairwise(X, operation):        
    # Initialise precomputed matrix
    precomputed = np.zeros((X.shape[0], X.shape[0]), dtype='int')
    # Initialise iterator over objects in X
    iterator    = combinations_with_replacement(range(X.shape[0]), 2)
    # Perform the operation on each pair
    for i, j in iterator:
        precomputed[i, j] = operation(X[i], X[j])           
    # Make symmetric and return
    return precomputed + precomputed.T - np.diag(np.diag(precomputed))

我们可以定义一个函数来显示两组的重叠量并将其放入pairwise函数中

def overlap(x, y):
    return len(set(x) & set(y))

请注意,此解决方案需要一个 numpy 数组,因此对于您的示例,我们需要在将数据输入函数之前对其进行修改

X = np.array([a, b, c, d])
print(pairwise(X, overlap))

这产生了结果

[[3 2 2 2]
 [2 3 2 1]
 [2 2 3 1]
 [2 1 1 3]]
于 2018-09-19T15:27:01.503 回答
1

您可以将 4 个列表放在一个 dict 中,将它们转换为集合,用于itertools.combinations_with_replacement生成 2 个 4 个列表之间的所有组合,将它们放入由frozenset键组合的 a 索引的 dict,其值是值集,并在嵌套循环中打印输出:

from itertools import combinations_with_replacement
d = {'a': [1,2,3], 'b': [2,3,4], 'c': [1,2,4], 'd': [1,3,6]}
s = {frozenset([a[0], b[0]]): len(a[1] & b[1]) for a, b in combinations_with_replacement([(k, set(v)) for k, v in d.items()], 2)}
print(' ', ' '.join(d))
for i in d:
    print(i, end=' ')
    for j in d:
        print(s[frozenset([i, j])], end=' ')
    print()

这输出:

  a b c d
a 3 2 2 2 
b 2 3 2 1 
c 2 2 3 1 
d 2 1 1 3 
于 2018-09-19T15:39:24.523 回答
0

通过使用方法np.in1d

import numpy as np
R = []
A = np.array([a,b,c,d])
for x in A:
    A = np.array([a,b,c,d])
    ind = np.in1d(A,x).reshape(np.size(A,0),np.size(A,1))
    A[~ind] = 0
    R.append(A.sum(1))

R = np.vstack(R)

使用 R:

array([[ 6,  5,  3,  4],
       [ 5,  9,  6,  3],
       [ 3,  6,  7,  1],
       [ 4,  3,  1, 10]])
于 2018-09-19T16:00:58.593 回答