不使用库SQLite 3 python以格式打印表

epggiuax  于 2023-09-29  发布在  Python
关注(0)|答案(3)|浏览(136)

我想从我的数据库打印数据在一个更好的格式,这是一个游戏,我做的。这是代码:

def read_all_tables(self):
        self.cursor.execute('SELECT Name, Gender, Age, Score, Date, Time FROM Link JOIN Scores ON  Score_ID = Scores.ID JOIN Player ON Player_ID = Player.id ORDER BY Score DESC')
        Data = self.cursor.fetchall()
        for Row in Data:
            print()
            for record in range(len(Row)):
               print(Row[record], end=" ")

输出为:

HAMMAD MALE 18 900 07/01/18 13:07:02 
HAMMAD MALE 18 850 07/01/18 13:30:11 
INDERVEER MALE 18 750 07/01/18 13:35:46 
HAMMAD MALE 18 500 07/01/18 13:08:29 
HAMMAD MALE 18 400 07/01/18 14:07:29 
PARSA MALE 18 300 07/01/18 13:36:58 
HADIA FEMALE 19 300 07/01/18 14:09:37 
MANAAL FEMALE 18 100 07/01/18 13:51:40 
MICHAL MALE 18 0 07/01/18 13:42:41 
HAMMAD MALE 18 0 07/01/18 13:44:04 
HADIA FEMALE 19 0 07/01/18 13:45:51 
MANAAL FEMALE 18 0 07/01/18 13:53:02 
JACK WEIRD 21 0 07/01/18 13:53:49 
HAMMAD MALE 18 0 07/01/18 13:54:44 
HAMMAD MALE 18 0 07/01/18 13:56:08 
MANAAL FEMALE 18 0 07/01/18 13:57:39 
PARSA MALE 18 0 07/01/18 13:58:25 
HAMMAD MALE 18 0 07/01/18 13:59:08 
HAMMAD MALE 18 0 07/01/18 14:10:37

我如何对齐它们并有一个列标题?我不想使用任何图书馆。

1mrurvl1

1mrurvl11#

使用字符串格式化功能:

formatted_row = '{:<10} {:<6} {:>6} {:>6} {:<9} {:<9}'
print(formatted_row.format("Name", "Gender", "Age", "Score", "Date", "Time"))
for Row in Data:
    print(formatted_row.format(*Row))

输出量:

Name       Gender    Age  Score Date      Time     
HAMMAD     MALE       18    900 07/01/18  13:07:02 
HAMMAD     MALE       18    850 07/01/18  13:30:11 
INDERVEER  MALE       18    750 07/01/18  13:35:46 
HAMMAD     MALE       18    500 07/01/18  13:08:29 
HAMMAD     MALE       18    400 07/01/18  14:07:29 
PARSA      MALE       18    300 07/01/18  13:36:58 
HADIA      FEMALE     19    300 07/01/18  14:09:37 
MANAAL     FEMALE     18    100 07/01/18  13:51:40 
...

注意事项

在这种方法中,我们硬编码列的宽度。为了动态调整列宽,我们必须做更多的工作。我希望这对你有用。

更新

为了动态调整宽度,我们需要遍历数据两次:第一次确定每列的最大宽度,第二次打印。

# Determine the longest width for each column
header = ("Name", "Gender", "Age", "Score", "Date", "Time")
widths = [len(cell) for cell in header]
for row in Data:
    for i, cell in enumerate(row):
        widths[i] = max(len(str(cell)), widths[i])

# Construct formatted row like before
formatted_row = ' '.join('{:%d}' % width for width in widths)

print('DEBUG: widths={!r}'.format(widths))
print('DEBUG: formatted_row={!r}'.format(formatted_row))

print(formatted_row.format(*header))
for row in Data:
    print(formatted_row.format(*row))

输出量:

DEBUG: widths=[9, 6, 3, 5, 8, 8]
DEBUG: formatted_row='{:9} {:6} {:3} {:5} {:8} {:8}'
Name      Gender Age Score Date     Time    
HAMMAD    MALE    18   900 07/01/18 13:07:02
HAMMAD    MALE    18   850 07/01/18 13:30:11
INDERVEER MALE    18   750 07/01/18 13:35:46
...

如果您对结果满意,可以删除DEBUG行。他们在那里展示代码是如何工作的。

ws51t4hk

ws51t4hk2#

对于标题,只需选择所需的文本,如

select 'Name    Gender    Age  ...';

要格式化数据,请使用printf()函数(请参阅https://sqlite.org/lang_corefunc.html#printf),如

select printf('%-20s %-6s  %2d ....', Name, Gender, Age, ...) from ...;

(根据需要进行调整。)

pn9klfpd

pn9klfpd3#

公认的答案对我不起作用,所以我自己做了一个类似的。

  • result替换为Data
  • 记住要添加row_factory,所以在执行SELECT * tables时,您可以使用标题,并将它们插入表的顶行。这就是前三行所做的。

代码的其余部分:

  • 创建列长度列表,最初使用0 * 第一行项目的数量(也是标题)填充它们。
  • 对于行中的每个单元格,如果单元格的宽度小于该列的最大宽度,则将最大值设置为当前单元格宽度。
  • 打印每行的单元格,用空格替换None,并添加偏移量。
cursor.row_factory = sqlite3.Row  
    result=cursor.execute(  'select rowlong as info,games,roms,disks,samples,roms_disks_samples as all_files           from stats' ).fetchall()
    result.insert( 0,  (result[0].keys()) )#insert column names as first row (position 0); 'cursor.row_factory = sqlite3.Row' must be used before

    int_offset = 2
    ls_int_max_column_length = [0] * len( result[0] )
    for row in result:
        for i in range(len(row)):
            int_cell_space = len(    str( row[i] )     )
            if ls_int_max_column_length[i] < int_cell_space:
                ls_int_max_column_length[i] = int_cell_space
    
    #print(ls_int_max_column_length)

    print("")
    for row in result:
        for i in range(len(row)):
            print ( str(row[i]).ljust( ls_int_max_column_length[i] + int_offset ).replace('None','    ') , end = " ")
            #print ( str(row[i]) , end = " ")
        print("")
    print("")

    cursor.row_factory = None #set it back to None

您可以手动操作,但不建议手动操作,如果长度发生变化怎么办:

print("")
    for row in result:
        print ( str(row[0]).ljust(38), str(row[1]).ljust(25).replace('None','    '), str(row[2]).ljust(21).replace('None','    '), str(row[3]).ljust(16).replace('None','    '), str(row[4]).ljust(8).replace('None','    '), str(row[5]).ljust(9).replace('None','    '))
    print("")

相关问题