【问题标题】:How to count items in list recursively如何递归计算列表中的项目
【发布时间】:2014-12-14 20:13:49
【问题描述】:

我希望递归地计算列表中的项目。比如我有一个list几个list:

a = ['b', 'c', 'h']
b = ['d']
c = ['e', 'f']
h = []

我试图找到一种方法来找出列表“a”的长度。但是在列表'a'中我有'b','c'和'h'......因此我的函数然后进入列表'b'并计算那里的元素数量......然后列出'c'然后最后列出“h”。

【问题讨论】:

  • 这些列表是由字符串还是其他列表组成的?您的示例使用字符串,但您的问题暗示您的意思是列表。或者您是否尝试将字符串映射到其他列表?
  • 好吧,可以把它想象成一棵二叉搜索树……每个节点都与它之前的一个节点相连……每个节点可能有多个节点连接到它上面……
  • 所以我猜 'b'、'c'、'h' 是例如节点 .. 和“节点”b、'd' 连接到它
  • 你想要总长度包括子列表的长度吗?
  • 在这种情况下,您是否希望 a 的长度包括其子项的长度?

标签: python list recursion


【解决方案1】:
b = ['d']
c = ['e', 'f']
h = []
a = [b,c,h]

def recur(l):
    if not l: # keep going until list is empty
        return 0
    else:
        return recur(l[1:]) + len(l[0]) # add length of list element 0 and move to next element

In [8]: recur(a)
Out[8]: 3

添加打印以帮助理解输出:

def recur(l,call=1):
    if not l:
        return 0
    else:
        print("l = {} and  l[0] = {} on recursive call {}".format(l,l[0],call))
        call+=1
        return recur(l[1:],call) + len(l[0])

如果你想得到更深的嵌套列表,你可以展平并得到 len():

b = ['d']
c = ['e', 'f',['x', 'y'],["x"]]
h = []
a = [b,c,h]
from collections import Iterable

def flatten_nest(l):
    if not l:
        return l
    if isinstance(l[0], Iterable) and not isinstance(l[0],basestring): # isinstance(l[0],str) <- python 3
        return flatten_nest(l[0]) + flatten_nest(l[1:])
    return l[:1] + flatten_nest(l[1:])


In [13]: len(flatten_nest(a))
Out[13]: 6

【讨论】:

  • 如果列表包含引用子列表名称的字符串,您也可以使用 locals()['list name'] 访问它们
  • 请给我一点时间来理解这一点。如果我有问题,我会发表评论。
  • @Parker,是的,我只是假设 OP 实际上有一个列表列表
  • @Ali,在代码中if语句前加一个print(l)会更有意义
  • @PadraicCunningham .. 好吧,我终于正确理解了这段代码。
【解决方案2】:

对我有用的解决方案是:

def recur(arr):
 if not arr:
  return 0
 else:
  return 1 + recur(arr[1:])

【讨论】:

  • 这不计算子列表,你可以调用 len()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2015-04-17
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
相关资源
最近更新 更多