3 回答

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個(gè)贊
是的,有,只需遍歷列表并從字典中獲取值:
lst =['a','b','c','d']
dct = {'d':'fourth' ,'a': 'first','b':'second','c':'third'}
result = [dct[i] for i in lst]
print(result)
輸出
['first', 'second', 'third', 'fourth']
作為旁注,不要使用內(nèi)置名稱作為變量名稱。上面的列表推導(dǎo)等價(jià)于以下for循環(huán):
result = []
for e in lst:
result.append(dct[e])
如果你想要一個(gè)更健壯的版本,你可以使用get方法并提供一個(gè)默認(rèn)值,如下所示:
lst =['a','b','c','d', 'f']
dct = {'d':'fourth' ,'a': 'first','b':'second','c':'third'}
result = [dct.get(e, 'missing') for e in lst]
print(result)
輸出
['first', 'second', 'third', 'fourth', 'missing']

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是使用的簡(jiǎn)單方法operator.itemgetter:
l =['a','b','c','d']
d = {'d':'fourth' ,'a': 'first','b':'second','c':'third'}
itemgetter(*l)(d)
('first', 'second', 'third', 'fourth')
您的代碼的問(wèn)題在于您正在迭代dict.items(),因此您將按照值在字典中出現(xiàn)的順序提取值。您想以相反的方式執(zhí)行此操作,從而通過(guò)迭代列表中的值以按相同順序從字典中獲取值。
通過(guò)使用,itemgetter您可以從 中的d所有元素中獲取l,因此正如我提到的那樣,這是一種更簡(jiǎn)潔的方法,也可以使用列表理解輕松完成。
添加回答
舉報(bào)