嵌套列表比较

时间:2013-03-21 19:21:28

标签: python list nested list-comprehension

Python noob在这里请耐心等待!我有一个如下所示的列表:

bookList = [("Wuthering Heights", "fred"), ("Everville", "fred"), ("Wuthering Heights", "dan")]

我要做的是编写一个查看每个嵌套列表的函数,并查看谁与谁共享书籍,具体取决于谁登录。例如,如果登录了dan,系统会说“弗雷德也有李子“。

我有一个字典,将hold用户名设置为键和密码作为其值。

当他们涉及任何嵌套的时候,我有点挣扎于列表理解,并且非常感谢帮助!

3 个答案:

答案 0 :(得分:2)

我不认为您现有的数据结构对此非常理想。我会做的是将它预先处理成一个字典,其键是用户名,值是书集。然后,您可以执行循环或列表理解,以将登录用户与所有其他用户进行比较,并查看是否存在任何共同点。所以:

from collections import defaultdict
bookdict = defaultdict(set)
for book, name in bookList:
    bookdict[name].add(book)
logged_in_user = 'fred'
for person, books in bookdict.items():
    if person == logged_in_user:
        continue
    common = books.intersection(bookdict[logged_in_user])
    if common:
        print '%s also has %s' % (person, ', '.join(common))

答案 1 :(得分:0)

def common_books(user):
    user_books = {b for b, u in bookList if u == user}
    for b, u in bookList:
        if b in user_books and u != user:
            print '{0} also has {1}'.format(u,b)

答案 2 :(得分:-1)

如果你想在列表中找到fred的书籍

filter(lambda x: x[1] == "fred", bookList)

另一个版本根据Bakuriu的评论。

class Session:
    def __init__(self):
        self.books = ["Wuthering Heights", "Everville"]
        self.username = "fred"

bookList = [("Wuthering Heights", "fred"), ("Everville", "fred"), ("Wuthering Heights", "dan")]

if __name__ == "__main__":

    session = Session()

    for book in bookList:
        if book[1] != session.username and book[0] in session.books:
            print "{} also has {}".format(book[1], book[0])