简体   繁体   English

包含对象属性和打印/返回对象Python的搜索列表

[英]Search list that contain object attribute and print/return object Python

I've got a object in which I'm searching if the attribute title matches with my search 我有一个要在其中搜索的对象,如果属性title与我的搜索匹配

class Something(object):
    def __init__(self,title):
        self.title = title

    def __str__(self):
        return "%s is the title " % self.title

How can I print the object when it's invoked? 调用对象后如何打印? Here is how I'm searching for it. 这是我正在寻找的方式。

search = " ".join(s[1:]).lower()
if any(search in str(a.title).lower() for a in something):
    print filter(lambda x: search in str(x.title),something)

If any(...) will check if any part of the search matches with my object's title and will return true if found anything. If any(...)将检查搜索的任何部分是否与我的对象的标题匹配,如果找到任何内容,则返回true。


filter(...) prints the object, but here is where I'm having issues with it prints: filter(...)打印对象, 但是这是我遇到问题的地方:


[<__main__.Something object at 0x0000000002C93B38>, <__main__.Something object at 0x0000000002D33828>]


I know that this is an object, why is it not printing through the __str__(self) method? 我知道这是一个对象,为什么不通过__str__(self)方法打印? How can I evoke the print function from my object Something ? 如何从我的对象Something调用打印功能?

Generally, I would create a filter first to get the items which match your criteria. 通常,我将首先创建一个过滤器以获取符合您条件的项目。 Then I would iterate over that and do whatever you want with it: 然后,我将对此进行迭代,并对其进行任何操作:

generator = (x for x in something if search in str(x.title).lower())
for item in generator:
   print item

The advantage here is that you do the filtering ahead of time (without filter ) and you only do the filtering test once. 这样做的好处是您可以提前进行过滤(不使用filter ),并且只进行一次过滤测试。

You're printing the string representation of the list , and not each item in the list. 您正在打印列表的字符串表示形式,而不是列表中的每个项目。

You can do: 你可以做:

print map(str, filter(lambda x: search in str(x.title),something))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM