我想交叉引用字典和django查詢集,以確定哪些元素分別具有唯一的dictionary['name']
和djangoModel.name
值。我現在做這個的方法是:Pythonic方法來解析特定屬性的字典列表?
- 創建詞典列表[「名」]值
- 創建djangoModel.name列表值
- 通過生成唯一值的列表檢查列入這些名單
這看起來如下:
alldbTests = dbp.test_set.exclude(end_date__isnull=False) #django queryset
vctestNames = [vctest['name'] for vctest in vcdict['tests']] #from dictionary
dbtestNames = [dbtest.name for dbtest in alldbTests] #from django model
# Compare tests in protocol in fortytwo's db with protocol from vc
obsoleteTests = [dbtest for dbtest in alldbTests if dbtest.name not in vctestNames]
newTests = [vctest for vctest in vcdict if vctest['name'] not in dbtestNames]
感覺unpythonic不得不根創建中間名稱列表(上面的第2行和第3行),以便能夠立即檢查包含。我錯過了什麼?我想我可以把兩個列表內涵在這樣一行:
obsoleteTests = [dbtest for dbtest in alldbTests if dbtest.name not in [vctest['name'] for vctest in vcdict['tests']]]
,但似乎很難遵守。
編輯: 這樣想的初始狀態:
# vcdict is a list of django models where the following are all true
alldBTests[0].name == 'test1'
alldBTests[1].name == 'test2'
alldBTests[2].name == 'test4'
dict1 = {'name':'test1', 'status':'pass'}
dict2 = {'name':'test2', 'status':'pass'}
dict3 = {'name':'test5', 'status':'fail'}
vcdict = [dict1, dict2, dict3]
我不能轉換成集,除非我剝下來的東西,只是名稱的字符串走差異化,但後來我失去訪問模型/字典的其餘部分,對吧?如果我在這兩種情況下擁有相同類型的對象,則只能在這裏設置。
你介意提供一些示例數據?這將使問題更容易可視化。但是,如果您只是在兩個不同的名稱列表中尋找唯一的成員,那麼不需要深入研究它,這似乎是比較兩個set()容器的最佳位置。 – jathanism 2011-04-11 15:44:27