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))
1
  • It's hard to say with an ad-hoc data structure like this that you don't even describe explicitly. Can you show us an example of the input and output? And/or use namedtuple instead of a list of lists where indices have a special meaning? Commented Jul 11, 2013 at 9:02

1 Answer 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.