将元组附加到列表,分配索引
我正在开发一个化学程序,该程序需要所有元素及其相应原子质量单位的列表,大致如下:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一个更简单的解决方案是使用 for 循环迭代文件:
An easier solution is to iterate over the file using a for loop:
假设这些行仅包含
C 12
等,并用空格分隔:或者如果您碰巧喜欢列表推导式:
请注意,我假设您不关心它是元组还是列表。如果是这样,只需投射它:
编辑:谢谢,史蒂文。
Assuming the lines only contain
C 12
and such, and are separated by spaces:Or if you happen to like list comprehensions:
Note that I assume that you didn't care if it was a tuple or a list. If so, just cast it:
Edit: thanks, Steven.
字典将是更好的数据结构。
像这样使用它:
A dictionary would be a better data structure.
Use it like this:
你的课程表明你是 Python 新手,所以我将尝试清理它并指出一些事情,而不完全重写它。这里的其他解决方案更清晰,但希望这能帮助您理解一些概念。
现在,当您想要加载原子序数时,您可以实例化 Chemistry 类并调用其 readAMU() 方法!
请记住,由于最后一行:
self.Atoms = Atoms
,Atoms
是c
实例的一部分。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.
Now, when you want to load the atomic numbers you can instantiate the
chemistry
class and call itsreadAMU()
method!Remember,
Atoms
is a part of thec
instance because of the last line:self.Atoms = Atoms
.享受。
enjoy.