Python列表理解与for循环

时间:2016-09-20 04:48:06

标签: python for-loop list-comprehension

我有很多类对象,"玩家"。当我使用for循环与LC时,我得到两种不同的行为......

Python 2.7

foo = something.blahObject
for i in foo:
    print i

给我我想要的东西..

Object1
Object2
...

如果我这样做

print [i for i in foo]

给我......

[<something.blahObject at 0x10af....>, <something.blahObject at 0x10f....>]

如果for循环和列表理解表现相似,为什么我会得到不同的结果?我错过了什么?谢谢!

2 个答案:

答案 0 :(得分:4)

列表中的对象将使用其__repr__方法,而自身打印的对象将使用__str__。这就是为什么当您使用for循环(将使用__str__)和使用列表理解(将使用__repr__)时获得不同的打印输出。

class ExampleObject(object):
    def __repr__(self):
        return 'ExampleRepresentation'

    def __str__(self):
        return 'ExampleString'

e = ExampleObject()
print e  # ExampleString
print [e]  # [ExampleRepresentation]

答案 1 :(得分:0)

print [i for i in mylist]在功能上与print mylist相同,后者打印mylist的字符串表示,这意味着方括号包含每个元素的字符串再现的逗号分隔列表。如果循环遍历mylist并使用print语句单独打印每个项目,它将遍历列表并打印每个项目的字符串表示。

有关更多信息,请对列表和循环进行更多研究。我推荐official Python tutorial