|

楼主 |
发表于 2022-1-30 15:32:19
|
显示全部楼层
- 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
- class Table:
- """
- 初始化 Table
- """
- def __init__(self, table: list):
- self.table = table
- self.length = len(self.table[0]), len(self.table)
- self.__check()
- """
- 检查 self.table 是否合法
- """
- def __check(self):
- temp = set([len(x) for x in self.table])
- if len(temp) != 1:
- raise Exception()
- """
- 渲染 self.table
- """
- def render(self):
- col_spaces = 4
- l = no_list_list(self.table)
- rendered = ""
- # 每列之间的空,存储到 col_spaces
- for i in l:
- if len(str(i)) > col_spaces - 4:
- col_spaces = len(str(i)) + 4
- # 正式渲染
- for i_i in range(len(self.table)):
- i = self.table[i_i]
- for j in i:
- rendered += str(j) + " " * (col_spaces - len(str(j)))
- if i_i != len(self.table) - 1:
- rendered += "\n" * (col_spaces // 2)
- return rendered
- print(Table([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).render())
复制代码 |
|