2015-06-08 51 views
-1

我有列表中的數組,我想從兩個不同的列表中計數數組中元素的數量,而不是計數列表項。計算列表中的數組的元素

代碼

import numpy as np 
def count_total(a,b): 
#count the total number of element for two arrays in different list 
x,y=len(a),len(b) 
result=[] 
for a1 in a: 
    for b2 in b: 
     result.append(x+y) 
return result 

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

print(count_total(a,b)) 
print(count_total(a,c)) 
print(count_total(b,c)) 

實際輸出

[3, 3] 
[4, 4, 4, 4] 
[3, 3] 

所需的輸出

[7,5] 
[6,6,4,4] 
[5,5] 

誰能幫助?

+0

目前尚不清楚你想要的輸出如何對應到你的輸入。 – user2357112

回答

2

它從你身上看到我想要的所有可能的方式來總結數組長度的例子。這可以通過itertools.product來實現。這裏是我的代碼:

from itertools import product 

def count_total(a,b): 
    return [sum(map(len, i)) for i in product(a, b)] 

該產品返回a和b各一個元素的所有可能的安排。然後,對於每個安排,我們從每個列表中取出安排中的部分,然後將它們與sum一起添加。

+0

謝謝。這真的很有幫助 – Xiong89

0

錯誤在第4行,x和y分配列表長度而不是數組長度。

更換線4-8

x,y=len(a),len(b) 
result=[] 
for a1 in a: 
    for b2 in b: 
     result.append(x+y) 

y= lambda x:len(x) 
result=[] 
for a1 in a: 
    for b1 in b: 
     result.append(y(a1) + y(b1))