我目前正在研究python,我對此比較陌生,所以我有一個串列'D'
D = {
'Dunwich': ['Blaxhall', 'Harwich'],
'Blaxhall': ['Dunwich', 'Harwich', 'Feering'],
'Harwich': ['Dunwich', 'Blaxhall', 'Tiptree', 'Claston'],
'Tiptree': ['Feering', 'Harwich', 'Claston', 'Maldon'],
'Feering': ['Blaxhall', 'Tiptree', 'Maldon'],
'Maldon': ['Feering', 'Tiptree', 'Claston'],
'Claston': ['Maldon', 'Tiptree', 'Harwich']
}
還有另一個串列“結果”
Result= ['Dunwich', 'Harwich', 'Claston', 'Maldon']
我想要的是從串列 D 中彈出,其中 D 的鍵和 Result 的項相同,例如,如果 Result 如上所述,那么在比較和彈出串列 D 之后應該是
D = {
'Dunwich': ['Blaxhall', 'Harwich'],
'Harwich': ['Dunwich', 'Blaxhall', 'Tiptree', 'Claston'],
'Maldon': ['Feering', 'Tiptree', 'Claston'],
'Claston': ['Maldon', 'Tiptree', 'Harwich']
}
我希望這個查詢是可以理解的,如果我在某個地方錯了,請糾正我,請幫我解決這個問題
uj5u.com熱心網友回復:
您可以使用 dict 理解:
D = {
'Dunwich': ['Blaxhall', 'Harwich'],
'Blaxhall': ['Dunwich', 'Harwich', 'Feering'],
'Harwich': ['Dunwich', 'Blaxhall', 'Tiptree', 'Claston'],
'Tiptree': ['Feering', 'Harwich', 'Claston', 'Maldon'],
'Feering': ['Blaxhall', 'Tiptree', 'Maldon'],
'Maldon': ['Feering', 'Tiptree', 'Claston'],
'Claston': ['Maldon', 'Tiptree', 'Harwich']
}
Result= ['Dunwich', 'Harwich', 'Claston', 'Maldon']
output = {x: D[x] for x in Result}
print(output)
# {'Dunwich': ['Blaxhall', 'Harwich'],
# 'Harwich': ['Dunwich', 'Blaxhall', 'Tiptree', 'Claston'],
# 'Maldon': ['Feering', 'Tiptree', 'Claston'],
# 'Claston': ['Maldon', 'Tiptree', 'Harwich']}
uj5u.com熱心網友回復:
這是解決方案:
D = {
'Dunwich': ['Blaxhall', 'Harwich'],
'Blaxhall': ['Dunwich', 'Harwich', 'Feering'],
'Harwich': ['Dunwich', 'Blaxhall', 'Tiptree', 'Claston'],
'Tiptree': ['Feering', 'Harwich', 'Claston', 'Maldon'],
'Feering': ['Blaxhall', 'Tiptree', 'Maldon'],
'Maldon': ['Feering', 'Tiptree', 'Claston'],
'Claston': ['Maldon', 'Tiptree', 'Harwich']
}
Result = ['Dunwich', 'Harwich', 'Claston', 'Maldon']
output = dict()
for i in Result:
output[i] = D[i]
print(output)
uj5u.com熱心網友回復:
有很多不同的方法,你可以使用這個
D = {
'Dunwich': ['Blaxhall', 'Harwich'],
'Blaxhall': ['Dunwich', 'Harwich', 'Feering'],
'Harwich': ['Dunwich', 'Blaxhall', 'Tiptree', 'Claston'],
'Tiptree': ['Feering', 'Harwich', 'Claston', 'Maldon'],
'Feering': ['Blaxhall', 'Tiptree', 'Maldon'],
'Maldon': ['Feering', 'Tiptree', 'Claston'],
'Claston': ['Maldon', 'Tiptree', 'Harwich']
}
Result= ['Dunwich', 'Harwich', 'Claston', 'Maldon']
for k in set(D) - set(Result):
del D[k]
print(D)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439268.html
標籤:Python python-3.x 列表 python-2.7
