【问题标题】:How can I take the string of names and preferences & add them to the dictionary with names as the key?如何获取名称和首选项字符串并将它们添加到以名称为键的字典中?
【发布时间】: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(",") 行的意图是什么?后续代码是否使用计算出的nameprefs 值? 应该吗?请阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 并自学发现这些疏忽。
  • 另外,请尝试根据您遇到的问题来命名您的问题,而不是您尝试完成的总体任务。由于无论如何您都应该尽最大努力首先诊断和研究问题,因此请使用反映您对问题的理解的问题标题。请参阅How to Ask 了解更多信息。

标签: python string dictionary methods


【解决方案1】:

所以这里的问题是您在数据副本上使用rstrip,但从未将其应用于原始数据。

问题

for movie in movietitles:
    movie=movie.rstrip() # Changes the (copy) of the data rather than the original
    # We still need to apply this back to movietitles

有几种方法可以解决这个问题!

# Using indexing
for _ in range(len(movietitles)):
    movietitles[_] = movietitles[_].rstrip()

或者我们可以通过列表理解来内联

# Using list comprehension
movietitles = [movie.rstrip() for movie in movietitles]

如另一个答案中所述,在处理 csv 数据时,建议使用 csv 解析器,但对于这种规模来说完全没有必要!希望这会有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2021-09-18
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 2016-03-24
    相关资源
    最近更新 更多