23k*_*23k 2 python recursion nested-lists flatten python-3.x
我终于开始使用 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)
Run Code Online (Sandbox Code Playgroud)
输出
>>> count( [1,2,3,[4,5,5],[[5,2,1],4,5],[3]], 1 )
Output: 1
Expected output: 2
有没有一种简单的方法可以在Python中展平嵌套列表?或者我可以用一种简单的方法来解释我的代码中存在嵌套列表的事实?
小智 5
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5774 次 |
最近记录: |