0

Python 菜鸟在这里,所以请多多包涵!我有一个看起来像这样的列表:

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

我要做的是编写一个函数,查看每个嵌套列表并查看谁与谁共享书籍,这取决于谁登录。例如,如果 dan 已登录,系统会说“fred also has李子”。

我有一本字典,将用户名设置为键,密码设置为值。

当它们涉及任何嵌套时,我在列表理解方面有点挣扎,我们将不胜感激!

4

3 回答 3

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))
于 2013-03-21T19:45:07.973 回答
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)
于 2013-03-21T20:19:34.330 回答
-1

如果你想得到弗雷德在列表中的书

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])
于 2013-03-21T19:25:04.707 回答