我有这个数据集,我需要对齐ID
,Date
和Title
的列。我不确定如何对齐这些以及如何添加标题?我无法使用tabulate
等任何第三方功能。有人可以告诉我如何做到这一点?我是初学者,只需要一些指导!
data_set = [['ID=j234hg\n'], ['Date=19 October 1969\n'], ['Title=court scene with cardinal richelieu\n'], ['ID=d45j5jkd\n'], ['Date=28 December 1969\n'], ['Title=THE ROYAL PHILHARMONIC ORCHESTRA GOES TO THE BATHROOM\n'], ['ID=s4k5jk\n'], ['Date=8 December 1970\n'], ['Title=crossing the atlantic on a tricycle\n'], ['ID=zd7u4h\n'], ['Date=19 October 1969\n'], ['Title=Bicycle Repair Man\n'], ['ID=f983\n'], ['Date=22 December 1970\n'], ['Title=Royal Episode 13 (or: The Queen Will Be Watching)\n'], ['ID=j8s74\n'], ['Date=15 September 1970\n'], ['Title=THE SEMAPHORE VERSION OF WUTHERING HEIGHTS\n'], ['ID=n4j6l3j\n'], ['Date=7 December 1972\n'], ['Title=Mr. Pither']]
for index,l in enumerate(data_set):
column_name,value = l[0].split("=")
if 'Title' == column_name:
data_set[index]="=".join([column_name+value.title()])
print (data_set)
rows = [ data_set[i:i+3] for i in range(0,len(data_set), 3)]
print (sum(sorted(rows, key = lambda r:r[0][0]), []))
它需要看起来像这样:
#ID Date Title
#d45j5jkd 28 December 1969 The Royal Philharmonic Orchestra Goes To The Bathroom
#f983 22 December 1970 Royal Episode 13 (Or: The Queen Will Be Watching)
答案 0 :(得分:0)
您可以使用Python3.x Format Specification Mini-Language对标题和data_set
进行格式化和对齐。
不幸的是,data_set
是list
的子lists
,因此我们需要Flatten list of lists开始有点混乱,然后在{{1}打印-loop使用named placeholders and string padding从展平列表中打印3个组:
for
输出:
data_set = [['ID=j234hg\n'], ['Date=19 October 1969\n'], ['Title=court scene with cardinal richelieu\n'],
['ID=d45j5jkd\n'], ['Date=28 December 1969\n'], ['Title=THE ROYAL PHILHARMONIC ORCHESTRA GOES TO THE BATHROOM\n'],
['ID=s4k5jk\n'], ['Date=8 December 1970\n'], ['Title=crossing the atlantic on a tricycle\n'],
['ID=zd7u4h\n'], ['Date=19 October 1969\n'], ['Title=Bicycle Repair Man\n'], ['ID=f983\n'],
['Date=22 December 1970\n'], ['Title=Royal Episode 13 (or: The Queen Will Be Watching)\n'],
['ID=j8s74\n'], ['Date=15 September 1970\n'], ['Title=THE SEMAPHORE VERSION OF WUTHERING HEIGHTS\n'],
['ID=n4j6l3j\n'], ['Date=7 December 1972\n'], ['Title=Mr. Pither']]
#First, flatten the list of lists to one list of strings
flist = [item for sublist in data_set for item in sublist]
print('{h1:10}{h2:20}{h3}'.format(h1='#ID', h2='Date', h3='Title'))
for i in range(0, len(flist), 3):
print('{id:10}{date:20}{title}'
.format(
id=flist[i].strip('\n').split('=')[1],
date=flist[i+1].strip('\n').split('=')[1],
title=flist[i+2].strip('\n').split('=')[1])
)
如果它没有完全回答你的问题,请随意发表评论 我道歉,因为它很乱,但它的确有效。我稍后会尝试清理它。与此同时,我希望它有所帮助。