首页 > 解决方案 > 无法解压不可迭代的对象/遍历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

我该如何解决?

标签: python

解决方案


试试这个:

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)

推荐阅读