我想为每个元素添加一个id,如果元素多次出现,应该在第一次出现时添加id,我不知道这个问题,谁能帮助我
输入:
omg = ['a', 'b', 'c', 'a', 'b', 1]
输出:
omg_id = [0, 1, 2, 0, 1, 3]
最佳答案
按出现顺序获取 ID 的小技巧解决方案,使用 defaultdict
:
from collections import defaultdict
omg = ['a', 'b', 'c', 'a', 'b', 1]
d = defaultdict(lambda: len(d)) # late binding allows d not to be defined yet
omg_id = [d[x] for x in omg]
# [0, 1, 2, 0, 1, 3]
默认工厂将当前数量的已知键分配给每个新键。由于键访问不仅返回而且分配值,defaultdict
在理解过程中“增长”。
关于python为列表中的每个元素添加一个id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51464020/