通过从字典中获取列表值来更改列表值 (Python)
Changing values of a list by getting them from a dictionary (Python)
所以我的列表如下所示:
['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']]
使用列表理解:
>>> 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"}
所以我的列表如下所示:
['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']]
使用列表理解:
>>> 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"}