Python将嵌套列表中相应索引处的值分组
给定一个嵌套有numpy列表的列表,我希望遍历每个对应列表中的每个索引,并根据元素跟踪计数,元素将存储到单个列表中 下面的最小可运行代码示例更好地说明了这个问题Python将嵌套列表中相应索引处的值分组,python,list,numpy,Python,List,Numpy,给定一个嵌套有numpy列表的列表,我希望遍历每个对应列表中的每个索引,并根据元素跟踪计数,元素将存储到单个列表中 下面的最小可运行代码示例更好地说明了这个问题 import numpy as np lst = [ np.array([1,0,1]), np.array([1,1,1]), np.array([2,2,1]) ] print(lst) #Problem, take count of each corresponding index within li
import numpy as np
lst = [
np.array([1,0,1]),
np.array([1,1,1]),
np.array([2,2,1])
]
print(lst)
#Problem, take count of each corresponding index within list
#If the element == 2, subtract one. If it's 1, add 1. 0 has no value
#Make the output just one list with the calculated count for each index
#Expected output:
#lst = [1, 0, 3]
# 1 in index 0 because there's two 1s in each lists first index, but a 2 subtracts one from the count
# 0 in index 1 since there's one 1 which brings the count to 1, but a 2 subtracts one from the count
# 3 in index 2 since there's three 1's, adding 3 to the count.
我已经从collections import defaultdict查看了,从itertools import groupby查看了,但除了对嵌套列表排序之外,我不知道如何使用它来做其他事情
如果此问题在我上面提供的两个源中,则表示歉意。如果所有内部数组的长度相同,则可以将其转换为二维数组以利用numpy矢量化:
# transform into two dimensional array
arr = np.array(lst)
# set -1 where values are equals to 2
t = np.where(arr == 2, -1, arr)
# sum across first axis (each corresponding positions on the inners lists)
res = t.sum(axis=0).tolist()
print(res)
输出
[1, 0, 3]
如何将多个元素指定给不同的值?例如,您将如何处理t=np.where(arr==2,-1,arr)和n=np.where(arr==1,5,arr),但仍然能够调用sum(axis=0).tolist()?@MachineMachzor您可以在同一数组中调用np.where两次?不知道我是否理解你的问题