0

ここにPythonnoobがあるので、我慢してください!私はこのようなリストを持っています:

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

私がやろうとしているのは、ネストされた各リストを調べて、誰が誰と本を共有しているかを確認する関数を作成することです。たとえば、danがログインしている場合、システムは「fredプラム"。

キーとしてユーザー名を保持し、値としてパスワードを保持する辞書を設定しています。

ネストされたものが含まれている場合、リスト内包表記に苦労しているので、助けていただければ幸いです。

4

3 に答える 3

2

I don't think your existing data structure is really ideal for this. What I would do would be to pre-process it into a dictionary whose keys are the usernames and the values are sets of books. Then you can do a loop or list comprehension to compare the logged-in user with all the other users and see if there is anything in common. So:

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)

バクリウのコメントによる別のバージョン。

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 に答える