Python find size of each sublist in a list

两盒软妹~` 提交于 2021-01-29 15:05:03

问题


I have a big list of floats and integers as given below. I want to find the length of each sublist by neglecting empty or single elements.

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

My present code:

list_len = []
for i in big_list: 
     list_len.append(len(i))

Present output:

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

Expected output:

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

回答1:


res = [len(l) for l in big_list if isinstance(l, list) and len(l)> 0]



回答2:


I would go for:

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]

which works with numpy arrays and tuple as well




回答3:


Use list comprehension with list type checking like this:

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]



回答4:


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



回答5:


you can use compressed list with if-else statements:

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


来源:https://stackoverflow.com/questions/59990774/python-find-size-of-each-sublist-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!