【问题标题】:Assign first word of each line to key in dictionary将每行的第一个单词分配给字典中的键
【发布时间】:2018-03-19 03:19:34
【问题描述】:

所以我有一个家庭作业的问题,要求使用一个文本文件来创建一个字典,其中包含作为学生姓名的键和作为 NumPy 1 维矩阵的对应值。

文本文件的格式如下:

John 23 53 54 56 58    
Jane 89 54 56 76 93    
Marie-Claire 56 68 76 86 92

所有名字都是一个单词或一个连字符的名字,并且所有学生在他们的文件行上都有相同数量的成绩。问题是我不知道如何只使用文本文件中每一行的第一个单词(名称)作为键。这是我的尝试:

def student_grade(filename):
    with open('filename','r') as file:
        Grade_Dict = {}
        for line in file:
            words = line.split(' ')
            Grade_Dict[words[0]]= np.array(words[1:])

注意:问题要求制作字典并在函数中读取文件。

我只是对如何测试这些代码是否正确感到困惑。

【问题讨论】:

  • 这又是怎么回事?如果您需要帮助测试它,只需通过您提供给我们的示例运行它。

标签: python function numpy dictionary


【解决方案1】:

你很亲密。几个小改动:

代码:

def student_grade(filename):
    with open(filename, 'rU') as file:
        grade_dict = {}
        for line in file:
            name = line.strip().split(' ')
            grade_dict[name[0]] = np.array(name[1:])
    return grade_dict

传递给open() 的文件名是一个变量,而不是字符串,所以filename 不是"filename"

测试代码:

print(student_grade('file1'))

结果:

{'John': array(['23', '53', '54', '56', '58'], dtype='<U2'), 
 'Jane': array(['89', '54', '56', '76', '93'], dtype='<U2'), 
 'Marie-Claire': array(['56', '68', '76', '86', '92'], dtype='<U2')
}

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    grade={}
    with open('file.txt','r') as f:
        for line in f:
            data=line.split()
            grade[data[0]]=np.array(list(map(int,data[1:])))
    print(grade)
    

    输出:

    {'Marie-Claire': array([56, 68, 76, 86, 92]), 'Jane': array([89, 54, 56, 76, 93]), 'John': array([23, 53, 54, 56, 58])}
    

    如果你不想要 int 中的数字,那么:

    grade={}
    with open('file.txt','r') as f:
        for line in f:
            data=line.split()
            grade[data[0]]=np.array(data[1:])
    print(grade)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2020-12-07
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多