python - Pandas - 在列表中,python查找每个子列表的大小

  显示原文与译文双语对照的内容

我有一个很大的浮点数和整数列表,如下所示,我想通过忽略空或单个元素来查找每个子列表的长度。


big_list = [[137.83,81.80,198.56],0.0,[200.37,151.55,165.26, 211.84],


 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]



我现在的代码:


list_len = []


for i in big_list: 


 list_len.append(len(i))



当前输出:


TypeError: object of type 'numpy.float64' has no len() 



预期输出:


list_len = [3,4,3,6,4,3] # list_len should neglect elements like 0, 4 in big_list. 



时间:

我愿意去:


big_list = [(137.83,81.80,198.56),0.0,np.array([200.37,151.55,165.26, 211.84]),


 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]



list_len = [len(x) for x in big_list if hasattr(x, '__len__') and len(x)>0]



它同样适用于numpy数组和元组

将列表推导与列表类型检查一起使用,如下所示:


big_list = [[137.83,81.80,198.56],0.0,[200.37,151.55,165.26, 211.84],


 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]



lengths = [


 len(sub_list) for sub_list in big_list if isinstance(sub_list, list)


]


print(lengths)



>>> [3, 4, 3, 6, 4, 3]




list(map(len, filter(lambda x: isinstance(x, list), big_list)))



可以在if-else语句中使用压缩列表:


list_len = [len(x) for x in big_list if isinstance(x,list)]



...