我终于在Python中进行递归并尝试计算list
中目标数的出现次数。但是,我遇到了在嵌套list
数字中计算出现次数的问题。
例如
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)
输出
>>> count( [1,2,3,[4,5,5],[[5,2,1],4,5],[3]], 1 )
Output: 1
Expected output: 2
有没有一种简单的方法可以在Python中展平嵌套列表?或者我可以通过一种简单的方法来解释代码中存在嵌套列表这一事实?
答案 0 :(得分:3)
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)
您只需要一个额外的案例来处理lst[0]
作为子列表,例如:
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)