ckblt 发表于 2022-1-25 22:23:37

【Python】命令行表格渲染器

本帖最后由 ckblt 于 2022-1-25 22:23 编辑

最近无聊编了一个命令行表格渲染器{:10_256:}
我给大家分享一下(有 BUG 请跟我说):

class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      if len(temp) != 1:
            raise Exception()

    """
    渲染 self.table
    """

    def render(self):
      col_spaces = []
      table2 = []
      rendered = ""

      # 把 table 的 x轴和 y轴互换,存储到 table2
      for i in range(self.length):
            temp = []
            for j in range(self.length):
                temp.append(str(self.table))
            table2.append(temp)

      # 每列之间的空,存储到 col_spaces
      for i in table2:
            j =
            col_spaces.append(max(*j) + 4)

      # 正式渲染
      for i in self.table:
            for j_i in range(len(i)):
                j = str(i)
                rendered += j + " " * (col_spaces - len(j))
            rendered += "\n"

      return rendered

使用方法(不会的话可以再问我):
t = Table([, , , ])
# [ ,
#   ,
#   ,
#    ]

print(t.render())
# 输出:
# 1   2   3
# 4   5   6
# 7   8   9
# 10    11    12

Passepartout 发表于 2022-1-26 08:42:50

{:5_108:}

python爱好者. 发表于 2022-1-30 13:52:14

等会,似乎和我的不太一样,你的似乎不能做到真正意义上的对齐:
这里将多为列表 list1 设置为:
list1 = [[-2,-1111111,0],,]
然后运行我们两个的代码,上面是我的,下面是你的:
list1 = [[-2,-1111111,0],,]
space = 0
string = ""
space_with_number = (len(str(max(,key = lambda x:len(str(x)))))) * 2 + space
space = []
for i in range(len(list1)):

    space.append( for each in each_row]) - len(list1):len( for each in each_row])]]).split())]])
space =
value =
i = 0
for x in zip(value,space):
    if i % 3 == 0:
      print()
    print(x + x * " ",end = "")
    i += 1
print()






class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      if len(temp) != 1:
            raise Exception()

    """
    渲染 self.table
    """

    def render(self):
      col_spaces = []
      table2 = []
      rendered = ""

      # 把 table 的 x轴和 y轴互换,存储到 table2
      for i in range(self.length):
            temp = []
            for j in range(self.length):
                temp.append(str(self.table))
            table2.append(temp)

      # 每列之间的空,存储到 col_spaces
      for i in table2:
            j =
            col_spaces.append(max(*j) + 4)

      # 正式渲染
      for i in self.table:
            for j_i in range(len(i)):
                j = str(i)
                rendered += j + " " * (col_spaces - len(j))
            rendered += "\n"

      return rendered
t = Table(list1)

print(t.render())

输出结果是:
-2            -1111111      0               
1               2               3               
4               5               6               
-2    -1111111    0   
1   2         3   
4   5         6   
上面是我的,下面是你的,我复制时可能有些差错,您可以自己试一下!
所以你的其实没有去设置对齐的代码!是不是!?{:10_277:}

ckblt 发表于 2022-1-30 13:56:10

不是呀,
我的输出是:
-2    -1111111    0   
1   2         3   
4   5         6   

ckblt 发表于 2022-1-30 13:56:52

python爱好者. 发表于 2022-1-30 13:52
等会,似乎和我的不太一样,你的似乎不能做到真正意义上的对齐:
这里将多为列表 list1 设置为:



不是呀

python爱好者. 发表于 2022-1-30 13:58:03

ckblt 发表于 2022-1-30 13:56
不是呀,
我的输出是:

我前面就是说你的输出的是:
-2    -1111111    0   
1   2         3   
4   5         6   

ckblt 发表于 2022-1-30 13:58:27

python爱好者. 发表于 2022-1-30 13:52
等会,似乎和我的不太一样,你的似乎不能做到真正意义上的对齐:
这里将多为列表 list1 设置为:



哦,不好意思,理解错了

ckblt 发表于 2022-1-30 14:00:19

我的表格是单独两个列之间的的对齐,你的是全部对齐,

python爱好者. 发表于 2022-1-30 14:00:21

ckblt 发表于 2022-1-30 13:56
不是呀

{:10_277:}但是您看这里第 1 列与第 2 列相差 4 个空格,
而第 2 列与第 3 列相差 11 个空格,所以没有对齐!

python爱好者. 发表于 2022-1-30 14:01:52

ckblt 发表于 2022-1-30 14:00
我的表格是单独两个列之间的的对齐,你的是全部对齐,

{:10_281:}没事,您列之间对齐都能做的这么精简,相信这对你来说也是十分轻松的事。

ckblt 发表于 2022-1-30 14:09:17

python爱好者. 发表于 2022-1-30 14:01
没事,您列之间对齐都能做的这么精简,相信这对你来说也是十分轻松的事。

按照你的建议改了改代码:
(里面用到了禁止套娃函数 no_list_list)
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


class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      if len(temp) != 1:
            raise Exception()

    """
    渲染 self.table
    """

    def render(self):
      col_spaces = 0
      l = no_list_list(self.table)
      rendered = ""


      # 每列之间的空,存储到 col_spaces
      for i in l:
            if i > col_spaces:
                col_spaces = len(str(i)) + 4

      # 正式渲染
      for i in self.table:
            for j in i:
                rendered += str(j) + " " * (col_spaces - len(str(j)))
            rendered += "\n"

      return rendered


print(Table([, , ]).render())

python爱好者. 发表于 2022-1-30 14:15:02

还是有 Bug :
list1 = [[-2123,-1121221,0],,]
space = 0
string = ""
space_with_number = (len(str(max(,key = lambda x:len(str(x)))))) * 2 + space
space = []
for i in range(len(list1)):

    space.append( for each in each_row]) - len(list1):len( for each in each_row])]]).split())]])
space =
value =
i = 0
for x in zip(value,space):
    if i % 3 == 0:
      print()
    print(x + x * " ",end = "")
    i += 1
print()






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


class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      if len(temp) != 1:
            raise Exception()

    """
    渲染 self.table
    """

    def render(self):
      col_spaces = 0
      l = no_list_list(self.table)
      rendered = ""


      # 每列之间的空,存储到 col_spaces
      for i in l:
            if i > col_spaces:
                col_spaces = len(str(i)) + 4

      # 正式渲染
      for i in self.table:
            for j in i:
                rendered += str(j) + " " * (col_spaces - len(str(j)))
            rendered += "\n"

      return rendered


print(Table(list1).render())

上面的是我的,下面的是你的,结果是:
-2123         -1121221      0               
1               3442            3               
4               5               6               
-2123   -11212210      
1       3442    3      
4       5       6      

你的最后两列怎么粘在一起了?!!!{:10_277:}

ckblt 发表于 2022-1-30 14:24:07

python爱好者. 发表于 2022-1-30 14:15
还是有 Bug :

上面的是我的,下面的是你的,结果是:


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


class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      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
                print(col_spaces)


      # 正式渲染
      for i in self.table:
            for j in i:
                rendered += str(j) + " " * (col_spaces - len(str(j)))
            rendered += "\n"

      return rendered


print(Table([[-2123,-1121221,0],,]).render())

python爱好者. 发表于 2022-1-30 14:29:49

还还还是有 BUG:
list1 = [[-2,-1213214234,0],,]
space = 5
string = ""
space_with_number = (len(str(max(,key = lambda x:len(str(x)))))) * 2 + space
space = []
for i in range(len(list1)):

    space.append( for each in each_row]) - len(list1):len( for each in each_row])]]).split())]])
space =
value =
i = 0
for x in zip(value,space):
    if i % 3 == 0:
      print()
    print(x + x * " ",end = "")
    i += 1











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


class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      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
                print(col_spaces)


      # 正式渲染
      for i in self.table:
            for j in i:
                rendered += str(j) + " " * (col_spaces - len(str(j)))
            rendered += "\n"

      return rendered


print(Table(list1).render())











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


class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      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
                print(col_spaces)


      # 正式渲染
      for i in self.table:
            for j in i:
                rendered += str(j) + " " * (col_spaces - len(str(j)))
            rendered += "\n"

      return rendered


print(Table(list1).render())


上面是我的,下面是你的,结果是:
-2                         -1213214234                0                        
1342                     2                        3                        
234                        5                        6                        6
15
-2             -1213214234    0            
1342         2            3            
234            5            6         
对齐是对齐了,可这多出来的 15 和 6 又是从何而来呢??!

python爱好者. 发表于 2022-1-30 14:30:30

中间那一段代码不算昂——刚才发的

ckblt 发表于 2022-1-30 14:33:58

python爱好者. 发表于 2022-1-30 14:29
还还还是有 BUG:




忘记删掉debug了

ckblt 发表于 2022-1-30 14:34:37

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


class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      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 in self.table:
            for j in i:
                rendered += str(j) + " " * (col_spaces - len(str(j)))
            rendered += "\n"

      return rendered


print(Table([[-2,-1213214234,0],,]).render())

python爱好者. 发表于 2022-1-30 14:53:57

还还还还还是有 BUG:
list1 = [[-2,-1213214234,0],,]
space = 5
string = ""
space_with_number = (len(str(max(,key = lambda x:len(str(x)))))) * 2 + space
space = []
for i in range(len(list1)):

    space.append( for each in each_row]) - len(list1):len( for each in each_row])]]).split())]])
space =
value =
i = 0
for x in zip(value,space):
    if i % 3 == 0:
      print()
    print(x + x * " ",end = "")
    i += 1











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


class Table:
    """
    初始化 Table
    """

    def __init__(self, table: list):
      self.table = table
      self.length = len(self.table), len(self.table)
      self.__check()

    """
    检查 self.table 是否合法
    """

    def __check(self):
      temp = set()
      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 in self.table:
            for j in i:
                rendered += str(j) + " " * (col_spaces - len(str(j)))
            rendered += "\n"

      return rendered


print(Table(list1).render())


上面是我的代码,下面是你的代码,结果是:
-2                         -1213214234                0                        
1342                     2                        3                        
234                        5                        6                        -2             -1213214234    0            
1342         2            3            
234            5            6         
上面是我的,下面是你的,
你这里负号的位置怎么偏了呀!!?{:10_277:}

python爱好者. 发表于 2022-1-30 14:54:39

说错了,结果是:
-2                         -1213214234                0                        
1342                     2                        3                        
234                        5                        6                        
-2             -1213214234    0            
1342         2            3            
234            5            6         

python爱好者. 发表于 2022-1-30 14:55:10

哎,不对,又打错了!
页: [1] 2 3 4
查看完整版本: 【Python】命令行表格渲染器