简体   繁体   English

返回函数的字典

[英]Return a dictionary of a function

I want to define a function, that reads a table of a textfile as a dictionary and than use it for returning specific values.我想定义一个函数,它将文本文件的表作为字典读取,然后将其用于返回特定值。 The keys are chemical symbols (like "He" for Helium,...).键是化学符号(如氦的“He”,......)。 The values return their specific atom masses.这些值返回其特定的原子质量。 I don't understand, what I have to do...我不明白,我该怎么办...

The first five lines of the textfile read:文本文件的前五行内容如下:

H,1.008 H,1.008

He,4.0026他,4.0026

Li,6.94李,6.94

Be,9.0122是,9.0122

B,10.81乙,10.81

Here are my attempts: (I don't know where to place the parameter key so that I can define it)这是我的尝试:(我不知道在哪里放置参数键以便我可以定义它)

def read_masses():
         atom_masses = {}
         with open["average_mass.csv") as f:
             for line in f:
             (key, value) = line.split(",")
             atom_masses[key] = value
             return(value)

m = read_masses("average_mass.csv)
print(m["N"])                          #for the mass of nitrogen   ```

once return has called, the code below it doesn't execute.一旦调用了 return,它下面的代码就不会执行。 What you need to return is the atom_masses not value and you have to place it outside the for loop您需要返回的是atom_masses不是value ,您必须将其放在 for 循环之外

def read_masses(file):
    atom_masses = {}
    with open(file) as f:
        for line in f:
            (key, value) = line.split(",")
            atom_masses[key] = value
    
    return (atom_masses)

m = read_masses("average_mass.csv")
print(m["H"])
>>> 1.008

Try:尝试:

def read_masses(name):
    data = {}
    with open(name, "r") as f_in:
        for line in map(str.strip, f_in):
            if line == "":
                continue
            a, b = map(str.strip, line.split(",", maxsplit=1))
            data[a] = float(b)
    return data


m = read_masses("your_file.txt")
print(m.get("He"))

Prints:印刷:

4.0026

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM