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

2024-09-27 21:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这样一个列表:

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

所以,一个包含两个元素的列表

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']]


Tags: 列表字典onefirstthreefoursecondfive
1条回答
网友
1楼 · 发布于 2024-09-27 21:30:03

使用列表理解:

>>> 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"}

相关问题 更多 >

    热门问题