计算lis中的数组元素

2024-04-18 09:04:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我在列表中有数组,我想从两个不同的列表中计算数组中元素的数量,而不是计算列表项的数量。你知道吗

代码

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]

有人能帮忙吗?你知道吗


Tags: 代码inimport元素列表for数量len
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相加。你知道吗

错误在第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)) 

相关问题 更多 >