我正在运行一个API来从网站上获取一些信息,该网站将信息存储在列表“ []”中。如何通过此信息运行一个for循环:
1)遍历for循环中的对象列表(特别是比较一个对象文本) 2)如果对象的一个值等于1个字,请将整个对象保存到新列表中
我尝试通过列表/对象运行for循环,但收到错误“列表对象不可调用”
tree = Et.fromstring(response.content)
for child in tree.findall('meterConsumption'):
for audit in child.findall('audit'):
for creator in audit.findall('createdBy'):
for ID in child.findall('id'):
print ('Entry ID: ',ID.text)
for use in child.findall('usage'):
print ('Use: ',use.text)
for cost in child.findall('cost'):
print ('Cost: ',cost.text)
for startdate in child.findall('startDate'):
print ('Startdate: ',startdate.text)
for enddate in child.findall('endDate'):
print ('Enddate: ',enddate.text)
#save object to list
allentries.append(Entry(ID.text,
use.text,
cost.text,
startdate.text,
enddate.text,
creator.text))
for x in allentries():
print (x.entryid)
我正在寻找对象中所有键值对的列表。例如,它想要:
如果创建者==“人类”,从这句话开始。将附加到该对象的所有信息添加到新对象列表
答案 0 :(得分:0)
当您尝试像调用函数一样调用列表时,会出现'list' object is not callable
错误。这是在您的倒数第二行中发生的情况:
for x in allentries():
print (x.entryid)
由于allentries
是您的列表,因此在其末尾加上()
就是“调用”它的语法,这对于不是函数的对象没有意义。所以正确的语法是:
for x in allentries:
print (x.entryid)
对于您的第二个问题,我建议您研究pandas
DataFrames作为在Python中处理表格数据的便捷方法。由于child.findall()
为您提供了要使用.text
从中提取文本的对象列表,因此您可以像这样将列表字典传递给DataFrame
构造函数:
import pandas as pd
# Initialize empty dataframe
allentries = pd.DataFrame()
for child in tree.findall('meterConsumption'):
for audit in child.findall('audit'):
for creator in audit.findall('createdBy'):
# Also touched up your indentation
for ID in child.findall('id'):
print ('Entry ID: ',ID.text)
for use in child.findall('usage'):
print ('Use: ',use.text)
for cost in child.findall('cost'):
print ('Cost: ',cost.text)
for startdate in child.findall('startDate'):
print ('Startdate: ',startdate.text)
for enddate in child.findall('endDate'):
print ('Enddate: ',enddate.text)
# Use list comprehensions to extract text attributes
allentries.append({
'ID': [ID.text for ID in child.findall('id')],
'use': [use.text for use in child.findall('use')],
'cost': [cost.text for cost in child.findall('cost')],
'startdate': [startdate.text for startdate in child.findall('startDate')],
'enddate': [enddate.text for enddate in child.findall('endDate')]
})
# Display the final dataframe
print(allentries)
答案 1 :(得分:0)
在for循环的child.findall('id')之后,三重for循环将导致称为identation error
的编译时错误。
for child in tree.findall('meterConsumption'):
for audit in child.findall('audit'):
for creator in audit.findall('createdBy'):
#identation error
for ID in child.findall('id'):
print ('Entry ID: ', ID.text)
列表对象不可调用意味着您试图调用列表对象。
allentries是一个列表,您正在尝试使用()
来调用列表。
删除此()
。