将嵌套列表中的唯一值替换为python中的数字

时间:2018-02-19 23:01:10

标签: 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]]

2 个答案:

答案 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