Recursively counting occurrences in a nested list of numbers
我终于开始在python中使用递归,并尝试计算在
例如
1 2 3 4 5 6 7 8 | def count(lst, target): if lst == []: return 0 if lst[0] == target: return 1 + count(lst[1:], target) else: return 0 + count(lst[1:], target) |
产量
埃多克斯1〔2〕
埃多克斯1〔3〕
江户十一〔四〕号
在python中是否有一种简单的方法来扁平嵌套列表?或者一个简单的方法来解释我的代码中有一个嵌套的列表?
1 2 3 4 5 6 7 8 | def count(lst, target): n = 0 for i in lst: if i == target: n += 1 elif type(i) is list: n += count(i, target) return n |
号
你只需要一个额外的案例来处理
1 2 3 4 5 6 7 8 9 10 11 12 | def count(lst, target): if lst == []: return 0 if lst[0] == target: return 1 + count(lst[1:], target) # If first element is a list, descend into it to count within it, # and continue with counts of remaining elements elif type(lst[0]) == list: return count(lst[0], target) + count(lst[1:], target) else: return 0 + count(lst[1:], target) |