0

is it possible to create nested filtering for list? I have a list of bookmarks that contains a list of tags. I want to filter for bookmarks with a specific tag.

def filterListByTag(bookmarkList, tag):
    filteredList = []
    #filter the list by single tag
    for b in bookmarkList:
        for t in b[1]:
            if t == tag:
                filteredList.append (b)
    return filteredList

I have coded a nested loop to achive this but is there a pythonic way using filter or [] like below ? :-)

 my_list = [i for i in my_list if i.attribute == value]
 filter(lambda x: x.attribute == value, my_list)

e.g.: I would like to get all bookmarks with the tag "newcar-7-seats"

Example of input :

print myBookmarks.bookmarks[0]
(u'http://qt-project.org/doc/qt-4.8/examples-itemviews.html', [u'Python'], u'Item Views Examples | Documentation | Qt Project', u'', datetime.datetime(2013, 7, 10, 13, 38, 9))

print myBookmarks.bookmarks[1]
(u'http://qt-project.org/doc/qt-4.8/model-view-programming.html', [u'Python'], u'Model/View Programming | Documentation | Qt Project', u'', datetime.datetime(2013, 7, 10, 13, 36, 23))

print myBookmarks.bookmarks[4]
(u'http://www.gebrauchtwagen.at/', [u'newcar-7-seats'], u'Gebrauchtwagen.at \u2013 Auto, Autos, Jahreswagen, Neuwagen, Oldtimer, Unfallwagen, Automarkt, Autob\xf6rse', u'', datetime.datetime(2013, 7, 9, 8, 37, 35))

print myBookmarks.bookmarks[5]
(u'http://www.car4you.at/Gebrauchtwagen', [u'newcar-7-seats'], u'car4you | Gebrauchtwagen, Autos, Fahrzeuge und Motorr\xe4der kaufen und verkaufen', u'', datetime.datetime(2013, 7, 9, 8, 37, 25))

Filtered List on

print myBookmarks.bookmarks[4] 
(u'http://www.gebrauchtwagen.at/', [u'newcar-7-seats'], u'Gebrauchtwagen.at \u2013 Auto, Autos, Jahreswagen, Neuwagen, Oldtimer, Unfallwagen, Automarkt, Autob\xf6rse', u'', datetime.datetime(2013, 7, 9, 8, 37, 35))

print myBookmarks.bookmarks[5]
(u'http://www.car4you.at/Gebrauchtwagen', [u'newcar-7-seats'], u'car4you | Gebrauchtwagen, Autos, Fahrzeuge und Motorr\xe4der kaufen und verkaufen', u'', datetime.datetime(2013, 7, 9, 8, 37, 25))
4

1 回答 1

2

This should be equivalent,

filteredList = [b for b in bookmarkList if tag in b[1]]

I also think you meant to break after your append otherwise you'd get multiples.

于 2013-07-11T09:01:52.307 回答