通过从字典中获取列表来更改列表的值(Python)

时间:2015-02-12 13:04:59

标签: python list dictionary list-comprehension

所以我有这个列表如下:

['One', 'Two', 'Three', 'Four']
['Five', 'Six', 'Seven']

所以,包含2个元素的列表

lst = [['One', 'Two', 'Three', 'Four'], ['Five', 'Six', 'Seven']]

然后我还有一个字典,我这样说:

numberDict = dict()

numberDict["One"] = "First"
numberDict["Two"] = "Second"
numberDict["Three"] = "Third"
numberDict["Four"] = "Fourth"
numberDict["Five"] = "Fifth"
numberDict["Six"] = "Sixth"
numberDict["Seven"] = "Seventh"

我的问题:如何让我的列表看起来像这样?用字典替换它的值?

lst = [['First', 'Second', 'Third', 'Fourth'], ['Fifth', 'Sixth', 'Seventh']]

1 个答案:

答案 0 :(得分:4)

使用列表理解:

>>> list_of_list = [['One', 'Two', 'Three', 'Four'], ['Five', 'Six', 'Seven']]
>>> [[numberDict.get(value, "") for value in lst] for lst in list_of_list]
[['First', 'Second', 'Third', 'Fourth'], ['Fifth', 'Sixth', 'Seventh']]

另外,请注意您也可以一次性初始化numbersDict

>>> numbers_dict = {"One": "First",
...     "Two": "Second",
...     "Three": "Third",
...     "Four": "Fourth",
...     "Five": "Fifth",
...     "Six": "Sixth",
...     "Seven": "Seventh"}