如何获得任意嵌套的列表列表中的元素总数? [英] How can I get the total number of elements in my arbitrarily nested list of lists?

查看:757
本文介绍了如何获得任意嵌套的列表列表中的元素总数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分配给变量my_list的列表. my_list的值是[[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]].我需要找到my_list的长度,但是len(my_list)仅返回3.我希望它返回11.是否有任何Python函数可以返回my_list嵌套列表的全部长度和所有长度.

I have a list assigned to the variable my_list. The value of my_list is [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]. I need to find the length of my_list, but len(my_list) only returns 3. I want it to return 11. Is there any Python functions that will return the full length of my_list nested lists and all.

示例:

Input
[[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]

Output
11

我希望这不仅适用于数字,还适用于字符串.

I would like if this worked for not only numbers, but strings also.

推荐答案

此函数对列表的长度进行计数,将除list以外的任何对象都计为长度1,并递归列表项以找到展平的长度,并且可以正常工作可以任意嵌套,直至解释器的最大堆栈深度.

This function counts the length of a list, counting any object other than list as length 1, and recursing on list items to find the flattened length, and will work with any degree of nesting up to the interpreters maximum stack depth.

def recursive_len(item):
    if type(item) == list:
        return sum(recursive_len(subitem) for subitem in item)
    else:
        return 1

注意:根据使用方式,可能要检查项目是否可迭代而不是检查其类型是否为list,以便正确判断元组的大小等.但是,检查对象是否可迭代将产生副作用,即对字符串中的每个字符计数而不是给字符串长度1赋值,这可能是不希望的.

Note: depending on how this will be used, it may be better to check if the item is iterable rather than checking if it has the type list, in order to correctly judge the size of tuples, etc. However, checking if the object is iterable will have the side effect of counting each character in a string rather than giving the string length 1, which may be undesirable.

这篇关于如何获得任意嵌套的列表列表中的元素总数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆