Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中XML数据上的For循环返回预期4倍的元素数_Python_Xml_For Loop - Fatal编程技术网

Python中XML数据上的For循环返回预期4倍的元素数

Python中XML数据上的For循环返回预期4倍的元素数,python,xml,for-loop,Python,Xml,For Loop,使用以下代码,我加载了一个包含电子邮件数据的XML文件 from xml.etree import ElementTree with open(xmlFile, "r") as f: xml = ElementTree.parse(f) 然后,我初始化所有变量(为简洁起见,在此处添加子集): 最后,尝试循环浏览电子邮件: for node in xml.findall(".//header"): index.append(node.attrib.get('index'))

使用以下代码,我加载了一个包含电子邮件数据的XML文件

from xml.etree import ElementTree

with open(xmlFile, "r") as f:
    xml = ElementTree.parse(f)
然后,我初始化所有变量(为简洁起见,在此处添加子集):

最后,尝试循环浏览电子邮件:

for node in xml.findall(".//header"): 
  index.append(node.attrib.get('index')) 
  sender.append(node.attrib.get('from')) 
  subject.append(node.attrib.get('subject')) 
  date.append(node.attrib.get('date'))
问题是,当我这样做时,我得到了错误的输出。现在,我不能提供数据,因为它是保密的,但我可以提供我认为应该足够让我朝着正确的方向寻找错误的地方

In [127]: nodes = xml.findall(".//header")
In [128]: len(nodes)
Out[128]: 12018

In [129]: len(index)
Out[129]: 48072

In [130]: nodes[0].attrib.viewkeys()
Out[130]: dict_keys(['index', 'from', 'read', 'headerLink', 'messageType', 'contentLink', 'state', 'messageId', 'date', 'folder', 'folderId', 'rawLink', 'subject'])

In [130]: index[0:3]
Out[131]: 
['0',
 '(NYTimes.com News Alert) nytdirect@nytimes.com',
 'Breaking News:  At Florida State, Football Eclipses Justice: Records Show Police Often Go Easy on Players']

In [132]: for node in xml.findall(".//header")[0:3]: print(node.attrib.get("index"))
0
1
2

有没有想过我错过了什么?我对Python非常陌生,但不懂编码,我看不出哪里出了问题。提前谢谢

从评论中我们可以看出你做到了-

index = sender = subject = date = []
当您执行上述操作时,它实际上只创建一个列表,并且所有名称-
索引
发件人
主题
日期
都指向该列表。显示所有名称都指向同一列表-

>>> index = sender = subject = date = []
>>> id(index)
8237464
>>> id(sender)
8237464
>>> id(subject)
8237464
>>> id(date)
8237464
当你这样做的时候-

for node in xml.findall(".//header"): 
  index.append(node.attrib.get('index')) 
  sender.append(node.attrib.get('from')) 
  subject.append(node.attrib.get('subject')) 
  date.append(node.attrib.get('date'))
所有4项都添加到单个列表中(所有名称/变量都引用了该列表)。这就是您在一个列表中看到所有数据的原因

您应该按照示例中给出的那样单独定义每个列表,而不是使用上述方法-

index = []
sender = []
subject = []
date = []

您是否在交互式python解释器中运行了4次
循环?没有重新初始化
索引
和其他列表?@AnandSKumar不,我没有。如果这是问题所在,
索引
中的前三个值仍然是[0,1,2],但整个值集将在位置12018处重复。正如您在上面所看到的,
index
中有一些值不应该存在,这意味着它不是在不重新初始化的情况下重新运行循环。这就是您的确切代码吗?你确定你也没有错误地将所有内容附加到
索引中吗?是的,这就是我的确切代码。你确定你没有这样做吗?
索引=sender=subject=date=[]
,以防万一?这就解决了问题。对于实际发生的事情也有很好的解释。帮助我学习并解决我的问题。谢谢你,阿南!
index = []
sender = []
subject = []
date = []