【问题标题】:Replace tokens from list of lists with int value from Dictionary用 Dictionary 中的 int 值替换列表列表中的标记
【发布时间】:2026-01-05 13:55:01
【问题描述】:

我有一个列表列表,每个列表中只有标记。

grade_lists = [['Very good', 'good', 'okay'], ['sufficient', 'bad', 'very bad']]

这本字典带有key = stringvalue = int

month_ids = {     'Very good': 1,
                  'good': 2,
                  'okay': 3,
                  'sufficient': 4,
                  'bad': 5,
                  'very bad': 6
                  }

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

grade_lists = [[1, 2, 3], [4, 5, 6]]

【问题讨论】:

    标签: python list dictionary integer token


    【解决方案1】:

    你可以用list comprehensions做到这一点:

    grade_lists = [['Very good', 'good', 'okay'], ['sufficient', 'bad', 'very bad']]
    month_ids = {'Very good': 1, 'good': 2, 'okay': 3, 'sufficient': 4, 'bad': 5, 'very bad': 6}
    grade_lists2 = [[month_ids[grade] for grade in sublist] for sublist in grade_lists]
    print(grade_lists2)
    

    【讨论】:

      【解决方案2】:

      你可以尝试遍历每个列表

      temp_list, new_list = [], []
      
      for glist in grade_lists:
          temp_list = []
          for token in glist:
              temp_list.append(month_ids[token])
          new_list.append(temp_list)
      

      输出:

      >>> new_list
      [[1, 2, 3], [4, 5, 6]]
      

      【讨论】:

      • 最好使用列表推导,因为使用append 会更改每个添加元素的列表大小,效率不高。对于像这样的小列表,它并不重要,但无论如何使用列表推导是更好的做法。
      最近更新 更多