简体   繁体   English

如何仅使用内置函数从 python 中的列表列表中生成格式良好的表

[英]How to produce a well-formatted table from a list of list in python only using built-in functions

I have a list of lists like:我有一个列表,如:

a = [[1, 10, 0.1], [2, 10, 0.2], [3, 11, 0.25]]

For each list (a list of 3 fields), I want to separate the fields into separate variables and print with appropriate formatting, with column names, dollar signs, clean spacing, nicely lined up, etc. for example:对于每个列表(包含 3 个字段的列表),我想将字段分隔为单独的变量并使用适当的格式、列名、美元符号、干净的间距、整齐排列等进行打印,例如:例子

I tried using zip() but what was printed out won't work if I want to sort the price or amount.我尝试使用zip()但如果我想对价格或金额进行排序,打印出来的内容将不起作用。 I'd be very grateful if anyone could help me with my question only using the built-in functions in Python.如果有人可以仅使用 Python 中的内置函数来帮助我解决我的问题,我将不胜感激。

There are lots of formatted output options in Python. Python中有很多格式化的output选项。 Just pick one.随便挑一个。

a = [[1, 10, 0.1], [2, 10, 0.2], [3, 11, 0.25]]

print( " ID  Amount  Rate")
for row in a:
    print( f"{row[0]:3d}   ${row[1]:3d}   {row[2]:4.2f}" )
for row in a:
    print( "{:3d}   ${:3d}   {:4.2f}".format(*row) )

Output: Output:

 ID  Amount  Rate
  1   $ 10   0.10
  2   $ 10   0.20
  3   $ 11   0.25
  1   $ 10   0.10
  2   $ 10   0.20
  3   $ 11   0.25

not a built-in function but have you tried using pandas?不是内置的 function 但您是否尝试过使用 pandas? takes care of allot of of that for you try:照顾分配给你尝试:

normal_list = [[1, 10, 0.1], [2, 10, 0.2], [3, 11, 0.25]]

prettier_dataframe = pandas.DataFrame([[1, 10, 0.1], [2, 10, 0.2], [3, 11, 0.25]], columns = ["col1", "col2", "col3"], index = ["row1", "row2", "row3"])

print(prettier_dataframe)

If you want to outsource the formatting to have a clean usage like this or similar如果您想将格式外包以进行此类或类似的干净使用

for data in your_seq:
    print(data)

then you can consider using a class and design the output there.那么您可以考虑使用 class 并在那里设计 output。 The advantage is a separation of formatting the data and the data itself.优点是格式化数据和数据本身的分离。 Here is one example with equal distributed length for each column using dataclass:这是一个使用数据类的每列具有相等分布长度的示例:

from dataclasses import dataclass


@dataclass
class Data:
    ID: int
    Amount: int
    Rate: float

    @property
    def column_length(self):
        return self.get_longest_column_length()

    @classmethod
    def get_longest_column_length(cls):
        return len(max(*vars(cls)["__annotations__"], key=len)) + 1

    @classmethod
    def print_headline(cls):
        length = cls.get_longest_column_length()
        for var in vars(cls)["__annotations__"].keys():
            print(f"{var:<{length}}", sep="", end="")
        print()

    def __repr__(self):
        return (
            f"{self.ID:<{self.column_length}}"
            f"$ {self.Amount:<{self.column_length - 2}}"
            f"{self.Rate:<{self.column_length}}"
        )

For the usage, you can directly create Data instances or transform the items of an existing list to Data instances like this:对于使用,您可以直接创建 Data 实例或将现有列表的项目转换为 Data 实例,如下所示:

a = [[1, 10, 0.1], [2, 10, 0.2], [3, 11, 0.25]]
data = map(lambda el: Data(*el), a)

Then you can do what I mentioned for the first code snippet:然后你可以做我提到的第一个代码片段:

Data.print_headline()
for date in data:
    print(date)

There is probably much space for optimization, here.这里可能有很大的优化空间。 And the low-level detail how to probably format your code is only moved away to the __repr__ method.而如何格式化代码的低级细节只移到了__repr__方法。 So regarding this, there is not really something new in comparison to other answers.因此,关于这一点,与其他答案相比,并没有什么新东西。 But you also mentioned但你也提到

appropriate formatting, with column names, dollar signs, clean spacing, nicely lined up, etc.适当的格式,包括列名、美元符号、干净的间距、整齐排列等。

, so I had the feeling that using a class could be helpful as a potential starting point for more sophisticated formatting problems and trying to go a bit into the direction of separation of concerns (formatting vs. data). ,所以我觉得使用 class 可能有助于作为更复杂的格式化问题的潜在起点,并尝试将 go 稍微转向关注点分离的方向(格式化与数据)。

The output for your provided data is:您提供的数据的 output 是:

ID     Amount Rate   
1      $ 10   0.1    
2      $ 10   0.2    
3      $ 11   0.25   

okay, built-in functions only好的,只有内置函数

a = [[1, 10, 0.1], [2, 10, 0.2], [3, 11, 0.25]]
col_names = ["col1", "col2", "col3"]
row_names = ["row1", "row2", "row3"]

print("       ", *(col +"   " for col in col_names))
for row in range(len(row_names)):
    row_data = (str(a[row][n])+"   "+(" "*(len(col_names[n])-len(str(a[row][n])))) for n in range(len(a[row])))
    print(row_names[row] ,"   ",*row_data)

it messy but heres a rundown,它很乱,但这里有一个破败,

the first print prints the column names followed by a few spaces fed by a generator of the col_names list (plus a few spaces at the beginning to make room for the row names)第一个打印打印列名,后跟由 col_names 列表的生成器提供的几个空格(加上开头的几个空格为行名腾出空间)

the for loop is to make sure to catch each row for 循环是为了确保捕获每一行

the row_data variable does the same thing as the generator at the beginning, but concatenates the data from list a with enough spaces to make up the difference between the length of the column names and the length of the data (so that the rows and columns line up) row_data 变量在开始时与生成器做同样的事情,但将列表 a 中的数据与足够的空格连接起来,以弥补列名长度和数据长度之间的差异(以便行和列行向上)

then the second print function just prints that line out with the row name at the beginning然后第二个打印 function 只是打印出行名开头的那一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用控制台的内置函数的情况下在Python中的整数列表中查找最小值和最大值 - How to find minimum and maximum among a list of integers in Python without using built-in functions from console 在不使用python内置函数的情况下计算或添加列表元素 - Count or add list elements without using python built-in functions Python 2.7 不使用内置函数的列表模式 - Python 2.7 Mode of list without using built-in functions Python:从内置列表类型VS过滤器继承,映射内置函数 - Python: inherit from the built-in list type VS filter, map built-in functions 在不使用内置函数的情况下反转列表 - Reverse a list without using built-in functions Python:我如何从内置列表类型继承? - Python: How can I inherit from the built-in list type? 如何获取python中的内置模块列表? - How to get a list of built-in modules in python? python2中是否有内置函数列表,这些内置函数已在python3中删除? - Is there a list of built-in functions in python2 that were removed in python3? Python - 为什么类列在内置函数列表中? - Python - Why are classes listed in the list of built-in functions? 如何在不使用内置函数的情况下使用while循环将类型str的列表转换为int? - How to convert list of type str to int using while loop , without built-in functions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM