# Python3之递归函数简单示例

### 递归求和

```            ```

# 递归

def

d_sum

(

L

)

:

if

not

L

:

return

0

else

:

return

L

[

0

]

+

d_sum

(

L

[

1

:

]

)

sum_l

=

d_sum

(

range

(

10

)

)

print

(

sum_l

)

```
```

```            ```
45

```
```

```            ```

# 递归

def

d_sum

(

L

)

:

# 打印该层级L

print

(

L

)

if

not

L

:

return

0

else

:

return

L

[

0

]

+

d_sum

(

L

[

1

:

]

)

# 构建 0-10 数字元素列表

L

=

[

i

for

i

in

range

(

10

)

]

sum_l

=

d_sum

(

L

)

print

(

sum_l

)

```
```
```            ```
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[6, 7, 8, 9]
[7, 8, 9]
[8, 9]
[9]
[]
45

```
```

### 处理任意结构

```            ```

def

dd_sum

(

L

)

:

tot

=

0

for

x

in

L

:

if

not

isinstance

(

x

,

list

)

:

tot

+=

x

else

:

tot

+=

dd_sum

(

x

)

return

tot

# 嵌套列表

L

=

[

1

,

[

2

,

3

]

,

[

4

,

[

5

,

6

,

7

]

,

8

]

,

9

]

sum_l

=

dd_sum

(

L

)

print

(

sum_l

)

```
```

```            ```
45

```
```

QQ号联系： 360901061

【本文对您有帮助就好】