【问题标题】:Changing values of a list by getting them from a dictionary (Python)通过从字典中获取列表值来更改列表的值(Python)
【发布时间】:2015-02-12 13:04:58
【问题描述】:

所以我有一个看起来像这样的列表:

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

【问题讨论】:

  • 这与你的问题没有直接关系,而是风格提示:你可以像numberDict = {"One": "First", "Two": "Second", "Three": "Third"}(等)一样创建你的字典,并为自己节省一些击键。
  • thnx 伙计,是的,这更短:)

标签: python list dictionary list-comprehension


【解决方案1】:

使用列表推导:

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

【讨论】:

    猜你喜欢
    • 2022-06-16
    • 2020-08-06
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多