python - 用 python 中的数字替换嵌套列表中的唯一值

标签 python list nested unique

如何用数字替换嵌套列表中的唯一值?

sample = [["P1","P13","P2","P2"],
          ["P2","P13P14","P1","P0","P1"],
          ["P1","P0","P3"],
          ["P17","P3","P15P15"],
          ["P1","P5"]]

从示例中,我可以创建一个唯一值列表:

unique_sample = sorted(list(set(x for l in sample for x in l)))

所需的输出是从 unique_sample 返回样本嵌套列表中每个值的索引

output = [[4,0,5,5],
          [5,7,4,0,4],
          [4,3,6],
          [8,6,2],
          [4,1]]

最佳答案

这是一种方法:

from itertools import chain

sample = [["P1","P13","P2","P2"],
          ["P2","P13P14","P1","P0","P1"],
          ["P1","P0","P3"],
          ["P17","P3","P15P15"],
          ["P1","P5"]]

d = {j: i for i, j in enumerate(sorted(set(chain(*sample))))}

result = [list(map(d.get, i)) for i in sample]

# [[1, 2, 6, 6],
#  [6, 3, 1, 0, 1],
#  [1, 0, 7],
#  [5, 7, 4],
#  [1, 8]]

关于python - 用 python 中的数字替换嵌套列表中的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48875455/

相关文章:

vb.net - 如何从 VB.NET 的列表中找到对象的索引?

javascript - Javascript 中使用 if/else 嵌套 for 循环

嵌套if语句的Python单元测试

python - 使用用于音频指纹识别的 Dejavu 库识别文件夹中所有文件的循环

python - NASNet-A 微调验证精度差

python - 尝试使用 input.exec 插件时权限被拒绝

c - 在列表中插入节点的副本(有条件)

c# - .NET - 什么是 "double pointer list"?

java - 显示带有嵌套 for 循环的 ASCII 菱形

python - 让子弹停留在同一个空间