【问题标题】:Replace string from nested list with value from Dictionary in Python [duplicate]用Python中字典的值替换嵌套列表中的字符串[重复]
【发布时间】:2021-04-21 05:31:03
【问题描述】:

我有一个列表列表

month_list = [['January', 'february', 'march'], ['april', 'may', 'june']]

这个字典的键 = 字符串,值 = int

month_ids = {     'January': 1,
                  'february': 2,
                  'march': 3,
                  'april': 4,
                  'may': 5,
                  'june': 6
                  }

我可以用字典中的整数替换列表中的字符串吗?

【问题讨论】:

    标签: python string list dictionary integer


    【解决方案1】:

    如果要保持初始列表的嵌套结构,可以将嵌套列表理解表达式写为:

    >>> id_list = [[month_ids[month] for month in month_set ] for month_set in month_list]
    >>> id_list
    [[1, 2, 3], [4, 5, 6]]
    

    但是,如果您需要 扁平化列表,那么您可以将 itertools.chain()列表理解 结合使用:

    >>> from itertools import chain
    
    >>> id_list = [month_ids[month] for month in chain(*month_list)]
    >>> id_list
    [1, 2, 3, 4, 5, 6]
    

    这里chain(*month_list) 将整理您的月份列表。然后我迭代一个月份列表,并在 list comprehension 表达式中使用month_ids[month] 创建另一个包含 monthid 的列表。

    【讨论】:

    • 感谢您的信息。抱歉,我是 python 新手,我已将列表更新为正确的列表列表。
    • 你能确认你的嵌套列表是['January, february, march']还是应该是['January', 'february, 'march']
    • 我认为第二个选项 ['January', 'february, 'march'] 对我来说会更有趣。
    • @new_guy_around 根据您最近的编辑更新了答案。但是,如果您在问题中遗漏了任何内容并且想要编辑可能会更改问题上下文的内容,那么请将其创建为单独的问题。因为您对要求更改的有问题的编辑使现有答案无效。
    • 好的,感谢您提供的信息。抱歉给大家带来了困扰
    【解决方案2】:

    这一行

    for i in range(len(month_list)):
        month_list[i] = months_ids[month_list[i]]
    

    month_list = [months_ids[x] for x in month_list]
    

    month_list = list(map(lambda x: months_ids[x], month_list))
    

    【讨论】:

      【解决方案3】:

      您可以使用maplambda

      map(lambda month: month_ids.get(month), month_list)
      

      【讨论】:

        【解决方案4】:

        希望添加此行。

        month_list = list(month_ids.values())
        

        【讨论】:

          猜你喜欢
          • 2014-04-09
          • 2019-09-06
          • 2023-01-23
          • 1970-01-01
          • 2016-01-07
          • 1970-01-01
          • 1970-01-01
          • 2019-01-25
          • 2017-11-02
          相关资源
          最近更新 更多