【Python】禁止列表套娃!
本帖最后由 ckblt 于 2022-1-26 13:10 编辑今天闲得没事干突发奇想做了个禁止列表套娃的函数,
把套娃的列表弄成不套娃的列表,
如:
[ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ] # 套娃
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] # 不套娃
(小插曲:我由于懒得翻译“禁止列表套娃”,直接写成“no_list_list”了{:10_282:} )
废话少说,上代码!
from typing import Union
def no_list_list(
x: Union, no_tuples: bool = False, no_sets: bool = False
) -> list:
"""
禁止列表套娃函数(使用递归)
返回值: 列表
### 参数:
x: 套娃的 列表 | 元组 | 集合
no_tuples: 禁止元组套娃
no_sets: 禁止集合套娃
### 例子:
```
no_list_list( [ [ [ 1, 2, 3, 4, 5 ] ] ] )
no_list_list( [ [ [ 1, 2, 3, 4, 5 ], 6 ], 7 ] )
```
"""
new_list = []
for i in x:
if (
(isinstance(i, list))
or (no_tuples and isinstance(i, tuple))
or (no_sets and isinstance(i, set))
):
new_list.extend(no_list_list(i, no_tuples, no_sets))
else:
new_list.append(i)
return new_list
如有疑问,请回复我哟!
青出于蓝 发表于 2022-1-26 13:04
想法很好~语法好像有很多问题......
发现了一个问题(list|tuple|set改成Union)
还有什么问题呢(我用的是Python3.10,没有报错) ckblt 发表于 2022-1-26 13:14
发现了一个问题(list|tuple|set改成Union)
还有什么问题呢(我用的是Python3.10,没有报错)
没问题了
页:
[1]