Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建行为类似于表的格式化字符串输出的简单方法_Python_List_Format_Tabular - Fatal编程技术网

Python 创建行为类似于表的格式化字符串输出的简单方法

Python 创建行为类似于表的格式化字符串输出的简单方法,python,list,format,tabular,Python,List,Format,Tabular,在我去重新发明轮子之前,我想检查一下是否有人已经想出了解决这个问题的办法 我有一个字符串列表,需要以表格格式打印出来。我从表中获取数据,这些表在某些单元格中可能有较长的数据字符串 如果我试图以最长的字符串作为列宽的基础,我可能会得到巨大的列宽 我想知道的是,是否已经存在将字符串数据附加到另一行的东西,该行仍然与当前行对齐(基本上将其视为强制自动填充的单元格) 实例 listObj=[“前置条件:”、“条件:”、“输出:”, '按钮关闭','-','速度未打开', “按钮已启用为关闭”,“已启用为

在我去重新发明轮子之前,我想检查一下是否有人已经想出了解决这个问题的办法

我有一个字符串列表,需要以表格格式打印出来。我从表中获取数据,这些表在某些单元格中可能有较长的数据字符串

如果我试图以最长的字符串作为列宽的基础,我可能会得到巨大的列宽

我想知道的是,是否已经存在将字符串数据附加到另一行的东西,该行仍然与当前行对齐(基本上将其视为强制自动填充的单元格)

实例
listObj=[“前置条件:”、“条件:”、“输出:”,
'按钮关闭','-','速度未打开',
“按钮已启用为关闭”,“已启用为打开”,
“速度为开”、“按钮激活为开”、“激活为关”,
“保持稳定正北”,“按钮状态为保持”,
'按钮状态为加速器超控,设置内容为开',
“伙计们,踩到奖牌的踏板”]
上面的列表最初是一个三乘五的表。所以我想把所有内容都打印在三列中。我遇到问题的地方是列表中倒数第二个字符串项。还有更多类似的例子,因为这是一个有点做作的例子。任何帮助都将不胜感激。我以前遇到过这个问题,所以我想问一下,因为我相信其他人也有过这个问题

期望结果 前置条件输出 按钮关闭-速度未打开 按钮启用处于关闭激活状态处于关闭状态速度处于打开状态 按钮状态为保持按钮状态为踏板至med 伙计们,这里有加速器 而且设置的东西是开着的
编辑:使用列表作为变量,我一直用它来攻击自己的脚这是一个相当硬编码的尝试,目的是了解你在寻找什么。检查范围时也几乎没有错误。我会让你处理的:)

旁注


使用“list”作为变量是不好的形式。这可能与内置列表类型冲突,应避免

这里有一种非常灵活的方法:

# a simple function to do our line-splitting per value
def split_value(value, width):
    result = []
    while len(value) > width:  # while our string is longer than allowed
        split_index = value.rfind(" ", 0, width)
        if split_index == -1:  # no space in our current chunk, we must do hard-break
            split_index = width - 1  # set the split to our column width point
        result.append(value[:split_index + 1])  # add the current slice as a sub-row
        value = value[split_index + 1:]  # remove the added slice from our data
    if value:  # there are leftovers from slicing, add them as the last piece
        result.append(value)
    return result

# and our main function...
def draw_table(data, columns, table_width, column_border=1):
    column_data = [data[i::columns] for i in range(columns)]  # split the data into columns
    column_width = table_width // columns - column_border  # max characters per column
    column_template = ("{} " * (columns - 1)) + "{}"  # a simple template for our columns
    empty_value = " " * (column_width + column_border)  # what to print when there's no value
    rows = len(max(column_data, key=len))  # in case we have more data in some of the columns
    for row in range(rows):  # lets print our rows
        row_data = [split_value(x[row], column_width) if len(x) > row else []
                    for x in column_data]  # lets populate our row
        subrows = len(max(row_data, key=len))  # number of subrows for the current row
        for subrow in range(subrows):  # lets go through each of them and print them out
            print(column_template.format(*[x[subrow].ljust(column_width+column_border)
                                           if len(x) > subrow else empty_value
                                           for x in row_data]))  # print our (split) row
这有点扭曲,但可以可靠地完成工作,如果你阅读评论,也不难理解。它应该完全满足您的要求(尽管您期望的结果似乎与列表中的数据不符):

这将产生:

Pre-Condition: Condition: Output: Button is OFF - Speed is not on Button Enabled is OFF Enabled is ON Speed is on Button Active is ON Active is OFF Hold steady true north Button States is HOLD Button States is Pedal to the medal here ACCELERATOR OVERRIDE guys AND Set stuff is on... One extra value to prove the flow 前置条件:条件:输出: 按钮关闭-速度未打开 按钮启用为关闭启用为打开速度启用 按钮激活处于打开状态激活处于关闭状态保持稳定正北 按钮状态是保持按钮状态是踏板到奖牌这里 加速器超控家伙 而且设置的东西是开着的。。。 一个额外的值 验证流程
将来的升级(如可变列宽)应该不会那么困难,因为行数据拆分是外部的,因此可以添加任何大小的数据。

hi,请查看python模块“tablate”,您如何知道如何对这些字符串进行分组?这只是一个简单的列表…请参阅我的中的
TextFormatter
类的代码。原始表基于三列格式,带有前置条件、条件,然后是输出。我添加了所需的结果,这与原始的格式化表有些相似。可能值得学习,它在jupyter笔记本中产生了非常好的数据帧输出。这正是我想要做的。它实际上会被粘贴到excel工作表中的一个单元格中。但是,我可以随时修改打印语句。excel不会为您包装字符串吗?是的。我在最初的问题中没有给出全部情况。这些是将上载到数据库的软件需求,excel部分是将它们上载到数据库的中间步骤。在一天结束时,数据最终会显示在某个地方,按照现在的方式,它只会转储一个没有格式的巨大文本球。所以,我试图对它进行格式化,这样测试人员就可以看到以前的表格格式。这是我问题范围内的正确答案。我也可以修改它来做我想做的事情。至于为什么我没有使用csv文件来做这个。我被提供给我的上传工具卡住了,这些工具与excel一起工作。你的原始答案适用于大多数数据。但是,在某些情况下,长字符串会导致while循环进入无限循环。我不知道是什么原因造成的。当我弄清楚是什么原因导致它时,我会编辑我的原始帖子。
mylist = ['Pre-Condition:', 'Condition:', 'Output:', 
        'Button is OFF', '-', 'Speed is not on', 
        'Button Enabled is OFF', 'Enabled is ON', 
        'Speed is on', 'Button Active is ON', 'Active is OFF', 
        'Hold steady true north', 'Button States is HOLD', 
        'Button States is ACCELERATOR OVERRIDE AND Set stuff is on <Stuff here>', 
    'Pedal to the medal here guys']

def printCell(row, cellWidth):
    while row != ["","",""]:
        lineformat = ("{:"+str(cellWidth) + "} | ") * 3
        cells=[]
        for n, cell in enumerate(row):
            p = cellWidth
            if len(cell) > cellWidth :
                p = cell[:cellWidth].rfind(" ")
                if p == -1: 
                    p = cellWidth
                row[n] = cell[p:]
            else:
                row[n] = ""
            cells.append(cell[:p])
        print(lineformat.format(*cells))

def printColumns(alist, colCount, colWidth):
    for n in range(0,len(alist)-1,colCount):
        printCell(alist[n:n+colCount], colWidth)
        print("-" * colWidth * colCount)

if __name__ == "__main__":
    printColumns(mylist,3,30)
Pre-Condition:                 | Condition:                     | Output:                        | 
------------------------------------------------------------------------------------------
Button is OFF                  | -                              | Speed is not on                | 
------------------------------------------------------------------------------------------
Button Enabled is OFF          | Enabled is ON                  | Speed is on                    | 
------------------------------------------------------------------------------------------
Button Active is ON            | Active is OFF                  | Hold steady true north         | 
------------------------------------------------------------------------------------------
Button States is HOLD          | Button States is ACCELERATOR   | Pedal to the medal here guys   | 
                               |  OVERRIDE AND Set stuff is on  |                                | 
                               |  <Stuff here>                  |                                | 
------------------------------------------------------------------------------------------
import csv
with open('output.csv', 'w') as f:
    csvOut = csv.writer(f, delimiter=',')
    for n in range(0,len(mylist)-1,3):
        csvOut.writerow(mylist[n:n+3])
# a simple function to do our line-splitting per value
def split_value(value, width):
    result = []
    while len(value) > width:  # while our string is longer than allowed
        split_index = value.rfind(" ", 0, width)
        if split_index == -1:  # no space in our current chunk, we must do hard-break
            split_index = width - 1  # set the split to our column width point
        result.append(value[:split_index + 1])  # add the current slice as a sub-row
        value = value[split_index + 1:]  # remove the added slice from our data
    if value:  # there are leftovers from slicing, add them as the last piece
        result.append(value)
    return result

# and our main function...
def draw_table(data, columns, table_width, column_border=1):
    column_data = [data[i::columns] for i in range(columns)]  # split the data into columns
    column_width = table_width // columns - column_border  # max characters per column
    column_template = ("{} " * (columns - 1)) + "{}"  # a simple template for our columns
    empty_value = " " * (column_width + column_border)  # what to print when there's no value
    rows = len(max(column_data, key=len))  # in case we have more data in some of the columns
    for row in range(rows):  # lets print our rows
        row_data = [split_value(x[row], column_width) if len(x) > row else []
                    for x in column_data]  # lets populate our row
        subrows = len(max(row_data, key=len))  # number of subrows for the current row
        for subrow in range(subrows):  # lets go through each of them and print them out
            print(column_template.format(*[x[subrow].ljust(column_width+column_border)
                                           if len(x) > subrow else empty_value
                                           for x in row_data]))  # print our (split) row
listObj = ['Pre-Condition:', 'Condition:', 'Output:',
           'Button is OFF', '-', 'Speed is not on',
           'Button Enabled is OFF', 'Enabled is ON',
           'Speed is on', 'Button Active is ON', 'Active is OFF',
           'Hold steady true north', 'Button States is HOLD',
           'Button States is ACCELERATOR OVERRIDE AND Set stuff is on <Stuff here>',
           'Pedal to the medal here guys']

# table with three columns, two spaces between columns and of total width of 80 characters
draw_table(listObj, 3, 80, 2)
Pre-Condition: Condition: Output: Button is OFF - Speed is not on Button Enabled is OFF Enabled is ON Speed is on Button Active is ON Active is OFF Hold steady true north Button States is HOLD Button States is Pedal to the medal here ACCELERATOR OVERRIDE guys AND Set stuff is on <Stuff here>
listObj = ['Pre-Condition:', 'Condition:', 'Output:',
           'Button is OFF', '-', 'Speed is not on',
           'Button Enabled is OFF', 'Enabled is ON',
           'Speed is on', 'Button Active is ON', 'Active is OFF',
           'Hold steady true north', 'Button States is HOLD',
           'Button States is ACCELERATOR OVERRIDE AND Set stuff is on...',
           'Pedal to the medal here guys', "One extra value to prove the flow"]

 draw_table(listObj, 3, 80, 2)
Pre-Condition: Condition: Output: Button is OFF - Speed is not on Button Enabled is OFF Enabled is ON Speed is on Button Active is ON Active is OFF Hold steady true north Button States is HOLD Button States is Pedal to the medal here ACCELERATOR OVERRIDE guys AND Set stuff is on... One extra value to prove the flow