2015-06-09 113 views
0

我有下面的代码可以帮助我使用数组减号矩阵,但系统返回错误在这一行union = total - zerozero实际上是交点的计数。如果我在union=total-zero前面发表评论#我可以通过输入total - zero手动在python窗口中获得我的答案。在这种情况下,totalzero是数组。Python:Array减矩阵 - TypeError:不支持的操作数类型为 - :'int'和'list'

import numpy as np 
import itertools 
from numpy import matrix,ones 
from itertools import product,chain,combinations,permutations,izip 
from collections import Counter 

#################################################################### 

def diffs(a,b): 
    # collect sliding window differences 
    # length of window determined by the shorter array 
    # if a,b are not arrays, need to replace b[...]-a with 
    # a list comprehension 
    n,m=len(a),len(b) 
    if n>m: 
     # ensure s is the shorter 
     b,a=a,b # switch 
     n,m=len(a),len(b) 
     # may need to correct for sign switch 
    result=[] 
    for i in range(0,1+m-n): 
     result.append(b[i:i+n]-a) 
    return result 

################################################################### 

def alldiffs(a,b): 
    # collect all the differences for elements of a and b 
    # a,b could be lists or arrays of arrays, or 2d arrays 
    result=[] 
    for aa in a: 
     for bb in b: 
      result.append(diffs(aa,bb)) 
    return result 

################################################################### 

def count_total(a,b): 
    #count the total number of element for two arrays in different list 
    #return [sum(map(len, i)) for i in product(a, b)] 
    y= lambda x:len(x) 
    result=[] 
    for a1 in a: 
     for b1 in b: 
      result.append(y(a1) + y(b1)) 
    return result 

################################################################## 

def count_zero(obj): 
    #count the total number of zero for two arrays in different list 
    if isinstance(obj,list): 
     return list(map(count_zero,obj)) 
    else: 
     return Counter(obj)[0] 

# define the 3 arrays 
# each is a list of 1d arrays 

a=[np.array([2,2,1,2]),np.array([1,3])] 
b=[np.array([4,2,1])] 
c=[np.array([1,2]),np.array([4,3])] 

comb_set = list(itertools.combinations([a,b,c],2)) 
for i, j in itertools.combinations([a,b,c],2): 
    all_diffs = alldiffs(i,j) 
    total = count_total(i,j) 
    zero = count_zero(all_diffs) 
    total = np.array(total) 
    total = total[: np.newaxis] 
    zero = np.array(zero) 
    union = total-zero 

任何人都可以帮助我吗?

+0

我相信你的最后一个'total' 属性,在片中,有一个很好的逗号。检查它 –

+0

而且,来自这个'alldiffs'? –

+0

alldiffs是一个已定义的函数。你的意思是'union = total,-zero'?它返回错误。 – Xiong89

回答

1

I can manually get my answer in python window by typing total - zero.

这工作,因为在这一点上,你可以使用最后totalzero

如果打印出来ij内环路(或仔细检查comb_set),你会发现,j从列表中有1件(一np.ndarray)到1变化到2元素的列表,然后再返回最后一次迭代中的元素列表。 1元素列表不会导致错误,但是2元素列表可以。

这显然是来自您的不同尺寸输入列表a,bc的结果。您可能需要考虑如何以不同方式处理abc(及其组合)。

+0

它使用这种方法解决。 CC =地图(分,总,零)。谢谢。 – Xiong89

相关问题