将元组附加到列表,分配索引

发布于 2024-12-14 03:22:00 字数 708 浏览 0 评论 0原文

我正在开发一个化学程序,该程序需要所有元素及其相应原子质量单位的列表,大致如下:

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)

我走在正确的轨道上吗?如果不是,我如何将两个值附加到一个元组中,分配每个值和索引,然后将其附加到一个列表中?

I'm working on a chemistry program which requires a list of all elements and their corresponding atomic mass units, something along the lines of:

Elements = [(H,1),(He,2)...(C,12)]

all the elements and their AMU are read from a file where each line is written like "C 12". I need to read the information from the file, append each line into its own tuple and then append the tuple to a list. Here's some code I've tried without success.

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)

Am I on the right track? If no, how would I append two values into a tuple, assign each value and index and then append this into a list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

暖树树初阳… 2024-12-21 03:22:00

一个更简单的解决方案是使用 for 循环迭代文件:

elements = []
with open("AtomAMU.txt") as f:
    for line in f:
        name, mass = line.split()
        elements.append((name, int(mass)))

An easier solution is to iterate over the file using a for loop:

elements = []
with open("AtomAMU.txt") as f:
    for line in f:
        name, mass = line.split()
        elements.append((name, int(mass)))
王权女流氓 2024-12-21 03:22:00

假设这些行仅包含 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')]

编辑:谢谢,史蒂文。

Assuming the lines only contain C 12 and such, and are separated by spaces:

result = []
for line in open('filename.txt'):
    result.append(line.split())

Or if you happen to like list comprehensions:

[l.split() for l in open('filename.txt')]

Note that I assume that you didn't care if it was a tuple or a list. If so, just cast it:

[tuple(l.split()) for l in open('filename.txt')]

Edit: thanks, Steven.

千紇 2024-12-21 03:22:00

字典将是更好的数据结构。

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

A dictionary would be a better data structure.

with open("AtomAMU.txt") as f:
    elements_amu = dict(line.split() for line in f)

Use it like this:

elements_amu['H']   # gets AMU for H
elements_amu.keys() # list of elements without AMU
我不会写诗 2024-12-21 03:22:00

你的课程表明你是 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

请记住,由于最后一行:self.Atoms = AtomsAtomsc 实例的一部分。

Your class demonstrates that you're new to Python, so I'll try to clean it up and point out some things without completely rewriting it. Other solutions here are cleaner, but hopefully this will help you understand some of the concepts.

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

Now, when you want to load the atomic numbers you can instantiate the chemistry class and call its readAMU() method!

>>> c = chemistry()
>>> c.readAMU()
>>> print c.Atoms

Remember, Atoms is a part of the c instance because of the last line: self.Atoms = Atoms.

澉约 2024-12-21 03:22:00

享受。

elementlist= []
datafile= open("AtomAMU.txt")
for elementdata in datafile:
    elementlist.append(elementdata.split(" "))

enjoy.

elementlist= []
datafile= open("AtomAMU.txt")
for elementdata in datafile:
    elementlist.append(elementdata.split(" "))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文