Python question - I have a List of Classes, how do I remove duplicates?
Am writing an App Engine application (it's a simple quest system for a game):
so I have a list
class Quest(db.Model):
name = db.StringProperty()
# note: I made about 10 different quest entities ( quest1 to quest10)
class User(db.Model):
completed_quests = db.StringListProperty() # to store keys of completed quests
# note: I made some fake data showing that the user completed 3 quests.
# user.completed_quests = ["key1","key2","key3"] - keys belong to the corresponding quests
so I query the user and his/her completed quests. user = User.get_by_key_name(userid)
then I query the of quests model all_quests = Quest.all()
the question is: how do I cross check my user.completed_quests list with all_quests?
my goal: I want to present to the user a web page, where he/she can see : - a list of completed quests AND - inc开发者_开发技巧omplete quests.
a method which I'm using:
# prepare a buffer
completed_quests = []
for quest in all_quests:
for k,completed_quest in enumerate(user.completed_quests):
if str(completed_quest) == str(quest.key()): # the point of detection
completed_quests.append(completed_quest)
# final product is a list of completed quest entites
but how do I do this for my incompleted quests?
You can use difference
:
all = set(quest.key() for quest in all_quests)
complete = set(completed_quests)
incomplete = all.difference(complete)
Try something like this:
quests = [(x.key(), x) for x in Quest.all.fetch(1000)]
incomplete_quests = [v for k, v in quests if k not in a_user.completed_quests]
This presumes, for simplicity, that you first converted your list of completed quests to a db.ListProperty(db.Key).
精彩评论