简体   繁体   中英

Why am I getting a generator object instead of an integer?

I am parsing some XML from a website using requests and bs4 :

import requests
from bs4 import BeautifulSoup as bs

r = requests.get("http://xml.skiddlecdn.co.uk/xml/affiliates/topsellers.xml")

if r.status_code == 200:
    data = bs(r.text, 'xml')
    raw_dates = data.find_all('date')
    dates = [date.string for date in raw_dates]
    for date in sorted(dates):
        print("{}. {}".format(i for i in range(1, len(dates))), date))
else:
    r.raise_for_status()

My expected result:

1. 2017-01-17
2. 2017-01-20
3. 2017-01-20
# etc...

My actual result:

<generator object <genexpr> at 0x06022B70>. 2017-01-17
<generator object <genexpr> at 0x06022B70>. 2017-01-20
<generator object <genexpr> at 0x06022B70>. 2017-01-20
# etc...

Why?

It prints a generator, because you pass it a generator. I'm assuming you just want to display the date with an index value. Why not use enumerate instead?

for i, date in enumerate(sorted(dates), 1):
    print("{}. {}".format(i, date))

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