如何用数字替换嵌套列表中的唯一值?
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/