gpt4 book ai didi

Python:文件内容到字典

转载 作者:行者123 更新时间:2023-11-28 20:40:25 25 4
gpt4 key购买 nike

Write a function that accepts a filename(string) of a CSV file which contains the information about student's names and their grades for four courses and returns a dictionary of the information. The keys of the dictionary should be the name of the students and the values should be a list of floating point numbers of their grades. For example, if the content of the file looks like this:

Mark,90,93,60,90
Abigail,84,50,72,75
Frank,46,83,53,79
Yohaan,47,77,74,96

then your function should return a dictionary such as:

out_dict = {'Frank': [46.0, 83.0, 53.0, 79.0],
'Mark': [90.0, 93.0, 60.0, 90.0],
'Yohaan': [47.0, 77.0, 74.0, 96.0],
'Abigail': [84.0, 50.0, 72.0, 75.0]}

这是我的代码:

def dict_from_file (file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
print (data)
output_dict = {}
for line in data:

file_pointer.close()
return (output_dict)

#Main Program
file_name = input("Enter the exact file name with its extension (.i.e., .txt): ")
result = dict_from_file (file_name)
print (result)

如您所见,for 循环中缺少语句。问题是我找不到任何逻辑来首先从文件中获取输入并将其粘贴到字典中。如果我打算提取每行一次,我将如何将它添加到以名称为键并以四个数字为值的字典中?

最佳答案

严格关注您的代码:

如果你打印出你读过的内容,你会注意到你有这个:

['Mark,90,93,60,90\n', 'Abigail,84,50,72,75\n', 'Frank,46,83,53,79\n', 'Yohaan,47,77,74,96']

因此,当您遍历列表中的每个项目时,为了让这个示例保持简单,您几乎可以提取第一个项目,现在它将成为您的键,然后取出列表中排除名称的部分并将每个项目转换到一个 float 。

所以,您几乎在寻找:

l = line.split(',')
output_dict[l[0]] = map(float, l[1:])

上面发生的事情是,您正在获取要迭代的每个项目,通过拆分“,”使其成为一个列表。然后您将获取列表中的第一项并将其作为您的 key 。然后要分配您的值,您必须使用 map 方法,该方法会将 list 中的每个项目映射到一个 float 。

您将对正在读取的每个 执行该操作。

所以,最后,您将拥有:

def dict_from_file (file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
print (data)
output_dict = {}
for line in data:
l = line.split(',')
output_dict[l[0]] = map(float, l[1:])
file_pointer.close()
return output_dict

#Main Program
result = dict_from_file ('stuff.txt')
print (result)

运行该代码,您将获得:

{'Frank': [46.0, 83.0, 53.0, 79.0], 'Yohaan': [47.0, 77.0, 74.0, 96.0], 'Abigail': [84.0, 50.0, 72.0, 75.0], 'Mark': [90.0, 93.0, 60.0, 90.0]}

关于Python:文件内容到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com