简体   繁体   中英

Iterating Generators in a For Loop in Python

I'm trying to parse XML from the National Weather Service ; printing the hourly temperature, a blank space, and the associated time of that hourly temperature.

Printing the temperatures simply requires a for loop. The problem is indexing the correct time-stamp while looping and printing each temperature. Example children in /data/time-layout look like this:

<layout-key>k-p1h-n1-0</layout-key>
<start-valid-time>2014-06-30T13:00:00-05:00</start-valid-time>
<end-valid-time>2014-06-30T14:00:00-05:00</end-valid-time>
<start-valid-time>2014-06-30T14:00:00-05:00</start-valid-time>
<end-valid-time>2014-06-30T15:00:00-05:00</end-valid-time>

The desired snippets are all and only "start-valid-time" nodes.

Here is the code I have so far:

import elementtree.ElementTree as ET
import urllib2  

url = "http://forecast.weather.gov/MapClick.php?lat=36.06000&lon=-94.16000&FcstType=digitalDWML"
tree = ET.parse(urllib2.urlopen(url))
forecast = tree.getroot()
i = int(0)

Temperatures = forecast.find("./data/parameters/temperature[@type='hourly']")

for HourTemperature in Temperatures:
    TimeStamps = forecast.findall("./data/time-layout/start-valid-time") #Reference 1
    print HourTemperature.text, "  ", TimeStamps[i].text #Reference 2
    i += 1

Running "python [program name].py" yields

TypeError: 'generator' object has no attribute '__getitem__'

Which makes sense when the above lines Reference 1 and 2 are wrong. I believe my problem is caused by a misunderstanding of generators.

Thank ya'll in advance.

Your code works fine here with a slight import modification that may have to do with me running python 2.7.4 on Ubuntu.

import xml.etree.ElementTree as ET

The rest works as is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM