[英]How to count items in nest list?
I'm trying to figure out how to count the number of items in a nest list. 我正在试图弄清楚如何计算嵌套列表中的项目数。 I'm stuck at how to even begin this.
我一直坚持如何开始这个。 For example if I were to do NestLst([]) it would print 0 but if I do
例如,如果我要做NestLst([])它将打印0但是如果我这样做
NestLst([[2, [[9]], [1]], [[[[5]]], ['hat', 'bat'], [3.44], ['hat', ['bat']]]]
it would return 9. Any help on how to begin this or how to do this would be great. 它将返回9.如何开始这个或如何做到这一点的任何帮助将是伟大的。
Thanks! 谢谢!
import collections
def NestLst(seq):
if isinstance(seq, str) or not isinstance(seq, collections.Iterable):
return 1
return sum(NestLst(x) for x in seq)
>>> NestLst([[2, [[9]], [1]], [[[[5]]], ['hat', 'bat'], [3.44], ['hat', ['bat']]]])
9
def total_length(l):
if isinstance(l, list):
return sum(total_length(x) for x in l)
else:
return 1
Your question contains the keyword: recursively . 您的问题包含关键字: 递归 。 Create a function that iterates over the list and if it finds a non-list item, adds one to the count, and if it finds a list, calls itself recusively.
创建一个遍历列表的函数,如果它找到一个非列表项,则向计数中添加一个,如果找到一个列表,则会自动调用。
The issue with your code its that you are using length instead of a recursive call. 您的代码的问题在于您使用的是长度而不是递归调用。
Here is a pythonic pseudocode: 这是一个pythonic伪代码:
def count(list):
answer = 0
for item in list:
if item is not a list:
answer += 1
else:
answer += number of items in the sublist (recursion will be useful here)
You could try to recursively call reduce() . 您可以尝试递归调用reduce() 。 Something like that:
像这样的东西:
>>> def accumulator(x,y):
... if isinstance(y, list):
... return reduce(accumulator,y,x)
... else:
... return x+1
...
>>> reduce(accumulator, [10,20,30,40] ,0)
4
>>> reduce(accumulator, [10,[20,30],40] ,0)
4
>>> reduce(accumulator, [10,20,30,40,[]] ,0)
4
>>> reduce(accumulator, [10,[20,[30,[40]]]] ,0)
4
>>> reduce(accumulator, [10*i for i in range(1,5)] ,0)
4
Some notices: 一些通知:
0
at the end the the reduce()
call is the initial value. 0
是reduce()
调用的初始值。 This might be a pitfall since when omitting it you still have a valid call, but the result will not be what you want.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.