my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]
# do someting
...
print(len(new_list))
>>> 9
I have a nested list in python. How should I go about reaching the number of elements of this list? I tried to use numpy but without success.
CodePudding user response:
Assuming a classical python list, this can typically be solved by recursion:
my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]
def nelem(l, n=0):
if isinstance(l, list):
return sum(nelem(e) for e in l)
else:
return 1
nelem(my_list)
# 9
collecting the elements:
my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]
def nelem(l, n=0, out=None):
if isinstance(l, list):
return sum(nelem(e, out=out) for e in l)
else:
if out is not None:
out.append(l)
return 1
x = []
n = nelem(my_list, out=x)
print(n)
# 9
print(x)
# [6, 36, 54, 5, 13, 3, 5, 'b', 2]
CodePudding user response:
use pythn built-in function len()then the name of the vaiable for the list in the bracket
CodePudding user response:
You can also simply iterate over the list.
my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]
elements_sum = 0
for i in my_list:
if type(i) == list:
elements_sum = len(i)
else:
elements_sum = 1
print(elements_sum)
CodePudding user response:
To make it more general, you need a way to flatten your sequence, regardless how nested it is.
Then just apply the len
function:
def flattened(iterable):
for obj in iterable:
if is_iterable(obj):
yield from flattened(obj)
else:
yield obj
def is_iterable(x):
if isinstance(x, str):
return False
try:
iter(x)
except TypeError:
return False
return True
Usage:
>>> l = [6, 36, [54, 5, ["bar", "baz"], 13, [3, 5], ["foo", [1, 2, 3]]]]
>>> list(flattened(l))
[6, 36, 54, 5, 'bar', 'baz', 13, 3, 5, 'foo', 1, 2, 3]
>>> len(list(flattened(l)))
13