如何用数字替换嵌套列表中的唯一值?
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]]
答案 0 :(得分: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]]
答案 1 :(得分:1)
您可以使用pandas:
dayType