我正在研究一个化学程序,该程序需要列出所有元素及其相应的原子质量单位,其中包括:
Elements = [(H,1),(He,2)...(C,12)]
从文件中读取所有元素及其AMU,其中每行写成“C 12”。我需要从文件中读取信息,将每一行附加到自己的元组中,然后将元组附加到列表中。这是我尝试过的一些代码没有成功。
class chemistry:
def readAMU():
infil = open("AtomAMU.txt", "r")
line = infil.readline()
Atoms = list()
Element = ()
while line !="":
line = line.rstrip("\n")
parts = line.split(" ");
element = parts[0]
AMU = parts[1]
element.append(Element)
AMU.append(Element)
Element.append(Atoms)
我是否在正确的轨道上?如果不是,我如何将两个值附加到元组中,分配每个值和索引然后将其附加到列表中?
答案 0 :(得分:5)
更简单的解决方案是使用for循环迭代文件:
elements = []
with open("AtomAMU.txt") as f:
for line in f:
name, mass = line.split()
elements.append((name, int(mass)))
答案 1 :(得分:3)
假设这些行只包含C 12
等,并用空格分隔:
result = []
for line in open('filename.txt'):
result.append(line.split())
或者如果您碰巧喜欢列表推导:
[l.split() for l in open('filename.txt')]
请注意,我假设您不关心它是元组还是列表。如果是这样,只需投下它:
[tuple(l.split()) for l in open('filename.txt')]
编辑:谢谢,史蒂文。
答案 2 :(得分:1)
字典将是更好的数据结构。
with open("AtomAMU.txt") as f:
elements_amu = dict(line.split() for line in f)
像这样使用:
elements_amu['H'] # gets AMU for H
elements_amu.keys() # list of elements without AMU
答案 3 :(得分:1)
你的课程表明你是Python的新手,所以我会尝试清理它并指出一些事情,而不是完全重写它。这里的其他解决方案更清晰,但希望这将有助于您理解一些概念。
class chemistry:
# Because this is a class method, it will automatically
# receive a reference to the instance when you call the
# method. You have to account for that when declaring
# the method, and the standard name for it is `self`
def readAMU(self):
infil = open("AtomAMU.txt", "r")
line = infil.readline()
Atoms = list()
# As Frédéric said, tuples are immutable (which means
# they can't be changed). This means that an empty tuple
# can never be added to later in the program. Therefore,
# you can leave the next line out.
# Element = ()
while line !="":
line = line.rstrip("\n")
parts = line.split(" ");
element = parts[0]
AMU = parts[1]
# The next several lines indicate that you've got the
# right idea, but you've got the method calls reversed.
# If this were to work, you would want to reverse which
# object's `append()` method was getting called.
#
# Original:
# element.append(Element)
# AMU.append(Element)
# Element.append(Atoms)
#
# Correct:
Element = (element, AMU)
Atoms.append(Element)
# If you don't make sure that `Atoms` is a part of `self`,
# all of the work will disappear at the end of the method
# and you won't be able to do anything with it later!
self.Atoms = Atoms
现在,当你想加载原子序数时,你可以实例化chemistry
类并调用它的readAMU()
方法!
>>> c = chemistry()
>>> c.readAMU()
>>> print c.Atoms
请注意,Atoms
是c
个实例的一部分,因为最后一行:self.Atoms = Atoms
。
答案 4 :(得分:0)
享受。
elementlist= []
datafile= open("AtomAMU.txt")
for elementdata in datafile:
elementlist.append(elementdata.split(" "))