代码之家  ›  专栏  ›  技术社区  ›  Jack Robson

无法通过python中的对象数组解包不可iterable对象/iteraing

  •  1
  • Jack Robson  · 技术社区  · 6 年前

    我想遍历一个URL对象数组中的所有对象

    class Url(object):
        pass
    
    a = Url()
    a.url = 'http://www.heroku.com'
    a.result = 0
    b = Url()
    b.url = 'http://www.google.com'
    b.result = 0
    c = Url()
    c.url = 'http://www.wordpress.com'
    c.result = 0
    
    urls = [a, b, c]
    
    for i, u in urls:
        print(i)
        print(u)
    

    但是,当我运行此脚本时,它会返回以下错误:

    TypeError: cannot unpack non-iterable Url object
    

    我该怎么解决这个问题?

    1 回复  |  直到 6 年前
        1
  •  3
  •   whackamadoodle3000    6 年前

    试试这个:

    class Url(object):
        pass
    
    a = Url()
    a.url = 'http://www.heroku.com'
    a.result = 0
    b = Url()
    b.url = 'http://www.google.com'
    b.result = 0
    c = Url()
    c.url = 'http://www.wordpress.com'
    c.result = 0
    
    urls = [a, b, c]
    
    for i in urls:
        print(i)
    

    遍历URL。要获取结果和URL(我认为您正在尝试这样做),请执行以下操作:

    class Url(object):
        pass
    
    a = Url()
    a.url = 'http://www.heroku.com'
    a.result = 0
    b = Url()
    b.url = 'http://www.google.com'
    b.result = 0
    c = Url()
    c.url = 'http://www.wordpress.com'
    c.result = 0
    
    urls = [a, b, c]
    
    for c,i in enumerate(urls):
        print("index is ",c)
        print(i.result)
        print(i.url)