问题
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.
Example:
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.
回答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
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.
回答2:
As an alternative, you can use flatten with len:
from compiler.ast import flatten
my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
len(flatten(my_list))
11
PS. thanks for @thefourtheye pointing out, please note:
Deprecated since version 2.6: The compiler package has been removed in Python 3.
Alternatives can be found here: Python 3 replacement for deprecated compiler.ast flatten function
回答3:
hack solution, someone had to post it. Convert list to string (leave the heavy lifting / recursion to __str__
operator) then count the commas, add 1.
>>> my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
>>> str(my_list).count(",")+1
11
(works for integers & floats, of course fails with strings because they can contain commas)
EDIT: this hack doesn't account for empty lists: we have to remove []
elements:
>>> my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4],[]]]] # added empty list at the end
>>> s = str(my_list)
>>> s.count(",")-s.count("[]")+1 # still 11
回答4:
You are essentially looking for a way to compute the number of leaves in a tree.
def is_leaf(tree):
return type(tree) != list
def count_leaves(tree):
if is_leaf(tree):
return 1
else:
branch_counts = [count_leaves(b) for b in tree]
return sum(branch_counts)
The count_leaves function counts the leaves in a tree by recursively computing the branch_counts of the branches, then summing those results. The base case is when the tree is a leaf, which is a tree with 1 leaf. The number of leaves differs from the length of the tree, which is its number of branches.
回答5:
This is an alternative solution, which might be not so performant, since it fills a new flattened list, which is returned at the end:
def flatten_list(ls, flattened_list=[]):
for elem in ls:
if not isinstance(elem, list):
flattened_list.append(elem)
else:
flatten_list(elem, flattened_list)
return flattened_list
flatten_list
intuitively flattens the list, and then you can calculate the length of the new returned flattened list with the len()
function:
len(flatten_list(my_list))
回答6:
Here is my implementation:
def nestedList(check):
returnValue = 0
for i in xrange(0, len(check)):
if(isinstance(check[i], list)):
returnValue += nestedList(check[i])
else:
returnValue += 1
return returnValue
回答7:
Easy Way for tuple
or list
For tuple
from nltk import flatten
Obj = (0.4, ((0.1, (0.05, 0.07)), (0.18, 0.2)))
print(len(flatten(list(Obj))))
For List
Obj = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
print(len(flatten((Obj))))
来源:https://stackoverflow.com/questions/27761463/how-can-i-get-the-total-number-of-elements-in-my-arbitrarily-nested-list-of-list