返回函数的字典



我想定义一个函数,它将文本文件中的表作为字典读取,然后使用它返回特定的值。关键是化学符号(比如"he")。氦,……)。这些值返回它们的特定原子质量。我不明白,我该怎么做……

文本文件的前五行为:

,

1.008,

4.0026李

6.94,

9.012210.81 B

这是我的尝试:(我不知道在哪里放置参数键,以便我可以定义它)

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   ```

一旦return调用,它下面的代码就不会执行。你需要返回的是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

尝试:

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"))

打印:

4.0026

相关内容

  • 没有找到相关文章

最新更新