【发布时间】:2021-12-10 02:00:00
【问题描述】:
我现在的代码如下所示:
def read_in_movie_preference():
"""Read the move data, and return a
preference dictionary."""
preference = {}
movies = []
# write code here:
file_location="./data/"
f = open(file_location+"preference.csv","r")
df = f.readlines()
#names as keys and prefrences
for line in df:
name = line[1].strip("\n").split(",")
prefs = line[2:].strip("\n").split(",")
preference[line[1]] = line[2:]
#print(test)
#movie names`
movietitles = df[0].strip("\n").split(",")
for movie in movietitles:
movie=movie.rstrip()
#can't seem to get rid of the spaces at the end
movies+=movietitles[2:]
print(movies)
return [movies, preference]
我似乎无法在其中一些末尾没有空格的情况下将电影标题添加到列表中,而且我也无法将名称和首选项添加到字典中...我应该使用基本的 python 来完成这项任务,而没有pandas .. 非常卡住将不胜感激!
字典将名称作为键和数字格式的偏好数字而不是字符串,因此理论上它看起来像这样: 键: 首选项: 丹尼斯,0 1 0 1 0 等
[![在此处输入图片描述][1]][1]这就是数据集的样子
这是粘贴的数据:
【问题讨论】:
-
我可以试试!
-
所以问题是您在数据副本上使用
rstrip,但从不将其应用于原始数据。替换为movietitles = [movie.rstrip() for movie in movietitles] -
“我似乎无法将电影标题放入列表中,其中一些末尾没有空格” 用您自己的话来说,
name = line[1].strip("\n").split(",")和prefs = line[2:].strip("\n").split(",")行的意图是什么?后续代码是否使用计算出的name和prefs值? 应该吗?请阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 并自学发现这些疏忽。 -
另外,请尝试根据您遇到的问题来命名您的问题,而不是您尝试完成的总体任务。由于无论如何您都应该尽最大努力首先诊断和研究问题,因此请使用反映您对问题的理解的问题标题。请参阅How to Ask 了解更多信息。
标签: python string dictionary methods