【发布时间】:2020-07-04 18:20:18
【问题描述】:
我写了这个程序:
with open("Films.txt","r") as f:
films=[]
newFilms=[]
for row in f:
field=row.split(",")
ID=field[0]
title=field[1]
year=field[2]
rating=field[3]
duration=int(field[4])
genre=field[5].strip()
newFilms.append(ID)
newFilms.append(title)
newFilms.append(year)
newFilms.append(rating)
newFilms.append(duration)
print(newFilms)
newFilms.append(newFilms)
newFilms=[]
sortedbyLength = sorted(films,key=lambda x:x[4],reverse=True)
print("%-5s %-20s %-20s %-20s %-20s %-20s"%("ID","Title","Year","Rating","Length (mins)","Genre"))
for i in range(len(sortedbyLength)):
print("%-5s %-20s %-20s %-20s %-20s %-20s"%(sortedbyLength[i][0],sortedbyLength[i][1],sortedbyLength[i][2],sortedbyLength[i][3],sortedbyLength[i][4],sortedbyLength[i][5]))
输出是这样的:
['001', 'Ghostbusters', '2016', 'PG', 116]
['002', ' The Legend of Tarzan', '2016', 'PG', 109]
['003', 'Jason Bourne', '2016', 'PG', 123]
['004', 'The Nice Guys', '2016', 'R', 116]
['005', 'The Scret Life of Pets', '2016', 'G', 91]
['006', 'Star Treck Beyond', '2016', 'PG', 120]
ID Title Year Rating Length (mins) Genre
这些打印语句的顺序错误,而不是我预期的顺序。谁能指出我在这里出错的地方? 谢谢!
【问题讨论】:
-
提示:让
pandas为您完成工作。将文件读入 DataFrame。 -
您希望
newFilms在newFilms.append(newFilms) ; newFilms=[]之后会是什么?另外,你的文件是 CSV,你应该使用csv模块来阅读它。 -
您希望它们按什么顺序排列?你有没有可能在你不想打电话的地方打电话给
reverse? -
不,它们的顺序正确。你的最后一个 for 循环永远不会运行,因为
sortedbyLength是空的,因为films是空的。 -
我认为您的意思是
films.append(newFilms)而不是newFilms.append(newFilms)