python中的嵌套列表过滤?

时间:2013-07-11 08:59:17

标签: python list

是否可以为列表创建嵌套过滤? 我有一个包含标签列表的书签列表。我想过滤具有特定标签的书签。

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

我已经编写了一个嵌套循环来实现这个但是有一个pythonic方式使用filter或[]如下所示? : - )

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

例如:我想获得所有带有“newcar-7-seat”标签的书签

输入示例:

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))

已过滤的列表

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 个答案:

答案 0 :(得分:1)

这应该是等价的,

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

我认为在你追加后你的意思是break否则你会得到倍数。