马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 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”了 )
废话少说,上代码!
- from typing import Union
- def no_list_list(
- x: Union[list, tuple, set], no_tuples: bool = False, no_sets: bool = False
- ) -> list:
- """
- 禁止列表套娃函数(使用递归)
- 返回值: 列表
- ### 参数:
- x: 套娃的 列表 | 元组 | 集合
- no_tuples: 禁止元组套娃
- no_sets: 禁止集合套娃
- ### 例子:
- ```
- no_list_list( [ [ [ 1, 2, 3, 4, 5 ] ] ] )
- [1, 2, 3, 4, 5]
- no_list_list( [ [ [ 1, 2, 3, 4, 5 ], 6 ], 7 ] )
- [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
复制代码
如有疑问,请回复我哟!
|