我有一个数据库里保存着许多化学物质和相应的数据,我如何返回一个特定的化学物质,和它的数据,通过它的公式,例如o2。你知道吗
class SourceNotDefinedException(Exception):
def __init__(self, message):
super(SourceNotDefinedException, self).__init__(message)
class tvorechoObject(object):
"""The class stores a pair of objects, "tv" objects, and "echo" objects. They are accessed
simply by doing .tv, or .echo. If it does not exist, it will fall back to the other variable.
If neither are present, it returns None."""
def __init__(self, echo=None, tv=None):
self.tv = tv
self.echo = echo
def __repr__(self):
return str({"echo": self.echo, "tv": self.tv}) # Returns the respective strings
def __getattribute__(self, item):
"""Altered __getattribute__() function to return the alternative of .echo / .tv if the requested
attribute is None."""
if item in ["echo", "tv"]:
if object.__getattribute__(self,"echo") is None: # Echo data not present
return object.__getattribute__(self,"tv") # Select TV data
elif object.__getattribute__(self,"tv") is None: # TV data not present
return object.__getattribute__(self,"echo") # Select Echo data
else:
return object.__getattribute__(self,item) # Return all data
else:
return object.__getattribute__(self,item) # Return all data
class Chemical(object):
def __init__(self, inputLine, sourceType=None):
self.chemicalName = TVorEchoObject()
self.mass = TVorEchoObject()
self.charge = TVorEchoObject()
self.readIn(inputLine, sourceType=sourceType)
def readIn(self, inputLine, sourceType=None):
if sourceType.lower() == "echo": # Parsed chemical line for Echo format
chemicalName = inputLine.split(":")[0].strip()
mass = inputLine.split(":")[1].split(";")[0].strip()
charge = inputLine.split(";")[1].split("]")[0].strip()
# Store the objects
self.chemicalName.echo = chemicalName
self.mass.echo = mass
self.charge.echo = charge
elif sourceType.lower() == "tv": # Parsed chemical line for TV format
chemicalName = inputLine.split(":")[0].strip()
charge = inputLine.split(":")[1].split(";")[0].strip()
mass = inputLine.split(";")[1].split("&")[0].strip()
# Store the objects
self.chemicalName.tv = chemicalName
self.charge.tv = charge
self.mass.tv = molecularWeight
else:
raise SourceNotDefinedException(sourceType + " is not a valid `sourceType`") # Otherwise print
def toDict(self, priority="echo"):
"""Returns a dictionary of all the variables, in the form {"mass":<>, "charge":<>, ...}.
Design used is to be passed into the Echo and TV style line format statements."""
if priority in ["echo", "tv"]:
# Creating the dictionary by a large, to avoid repeated text
return dict([(attributeName, self.__getattribute__(attributeName).__getattribute__(priority))
for attributeName in ["chemicalName", "mass", "charge"]])
else:
raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise print
from ParseClasses import Chemical
allChemical = []
chemicalFiles = ("/home/temp.txt")
for fileName in chemicalFiles:
with open(fileName) as sourceFile:
for line in sourceFile:
allChemical.append(Chemical(line, sourceType=sourceType))
for chemical in allChemical:
print chemical.chemicalName #Prints all chemicals and their data in list format
for chemical in allChemical(["o2"]):
print chemical.chemicalName
输出以下错误,我试图弥补没有运气; TypeError:“list”对象不可调用
尝试此功能:
此函数使用
toDict()
类中的Chemical
方法。从Chemical
类粘贴的代码解释了此方法从化学对象返回字典:这本词典是这样的:
我在上面创建的函数所做的是遍历列表中的所有化学品,找到第一个名称等于“o2”的化学品,并返回该化学品。使用方法如下:
如果上述方法不起作用,可能需要尝试使用替代优先级(“tv”),但我不确定这是否会产生任何影响:
如果没有找到化学物质,函数返回
None
:编辑:查看我的新答案。把这个留在这里,因为它可能仍然是有用的信息。你知道吗
在python中,list对象是一个包含其他对象的结构,它包含的每个对象都有一个索引。像这样:
如果要访问其中一个对象,必须知道其索引:
如果您不知道索引,可以使用
index
方法找到它:然后可以使用找到的索引从列表中获取对象:
但是这有点傻,因为你可以:
在这种情况下会产生相同的结果。你知道吗
你的
allChemical
对象是一个列表。看起来行chemicalFiles = ("/home/temp.txt")
正在用某种类型的对象填充您的列表。为了回答您的问题,您必须提供有关列表中包含的对象的更多信息。我假设信息在您正在使用的ParseClasses
模块中。你知道吗如果您可以提供有关正在导入的
Chemical
对象的更多信息,这可能会大大有助于解决您的问题。你知道吗如果列表中包含的对象是来自
str
的子类,则这可能起作用:"02"
是str
对象,因此index
将在列表中查找str
对象(或str
的子类对象)以查找其索引。但是,如果对象不是字符串,它将找不到它。你知道吗作为学习练习,请尝试以下方法:
这是因为索引能够找到您要查找的内容。如果它不是一个字符串,它就找不到它,如果你不知道“o2”是什么索引,如果你想得到你的化学品列表中的一种特定的化学品,你就必须了解更多关于这些物体的信息。你知道吗
问题是这两条线
allChemical
是一个列表,你不能只做a_list()
。看起来您正在试图在列表中找到['o2']
或只是'o2'
。为此,您可以获取该项的索引,然后从列表中获取该索引。你知道吗相关问题 更多 >
编程相关推荐