【问题标题】:How to convert list of strings to integer indexes?如何将字符串列表转换为整数索引?
【发布时间】:2021-08-17 09:39:42
【问题描述】:

我有一个这样的列表:

 lst = [['ab', 'bc', 'cd'], ['dg', 'ab']]

我想建立一个字符串索引器并将其转换为:

 lst_converted = [[1,2,3], [4,1]]

对转换后的列表做一些处理,然后如果输出是[[3], [2]]

 lst_output = [['cd'], ['ab']]

这里,

  'ab' = 1
  'bc' = 2
  'cd' = 3
  'dg' = 4

字符串可以是任意的,不一定是字符。如何做到这一点?

【问题讨论】:

  • Strings can be arbitrary and not necessarily characters ...那你应该举一个更一般的例子。
  • 修改了示例。

标签: python-3.x list indexing


【解决方案1】:

使用列表推导和字典将字符串文字映射到整数值:

d = {}
d['ab'] = 1
d['bc'] = 2
d['cd'] = 3
d['dg'] = 4

lst = [['ab', 'bc', 'cd'], ['dg', 'ab']]
lst_converted = [[d[y] for y in x] for x in lst]
print(lst_converted)  # [[1, 2, 3], [4, 1]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 2021-06-18
    • 2022-12-18
    相关资源
    最近更新 更多