无法解包不可迭代的对象/通过python中的对象数组进行迭代

时间:2018-07-14 12:45:21

标签: python

我要遍历我拥有的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 个答案:

答案 0 :(得分:3)

尝试一下:

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。要获取结果和网址(我认为您正在尝试这样做),请执行以下操作:

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)