我想将一个字符串列表存储到一个双元数据结构中,其中键将是我提供的字符串,值将是一个自动增量计数。
text = ['hello', 'world', 'again']
ai_ds = {} # define the data structure here, used dict just for reference
ai_ds.add(text[0]) # should return 0
ai_ds.add(text[1]) # should return 1
auto_increment_ds.get(text[0]) # should return 0我可以保留一个手动计数器,然后在字典中插入值时使用它,但我想知道python中是否存在这样的默认数据结构。
发布于 2022-07-22 20:21:38
带有setdefault的dict会运行得很好:
d = {}
d.setdefault("a", len(d))
d.setdefault("b", len(d))
d.setdefault("a", len(d))
print(d) # a=0, b=1发布于 2022-07-23 19:55:14
如果字符串值是唯一项,则:
text = ['hello', 'world', 'again']
d = {}
d[text[0]] = len(d)
d[text[1]] = len(d)
d[text[2]] = len(d)
print(d)
{'hello': 0, 'world': 1, 'again': 2}https://stackoverflow.com/questions/73085690
复制相似问题