我需要获取一个整数
n
并将其所有数字添加到 Python 字典 (哈希表) 中,以便稍后以 O(1)
的复杂性访问它们。
n = 941726149
d = {}
for i in str(n):
d[i] = None
print(d)
问题是当存在重复数字时,字典会覆盖它们并更改其顺序。例如,上面的代码输出:
{'9': None, '4': None, '1': None, '7': None, '2': None, '6': None}
但是我需要的输出是:
{'9': None, '4': None, '1': None, '7': None, '2': None, '6': None, '1': None, '4': None, '9': None}
我知道将重复键添加到哈希表中是不可能,所以我想知道是否可以修改该数据结构以适应这种行为,或者使用另一个支持它的
(maybe custom)
结构。
输入和输出示例:
这是一个示例,对于数字中出现的每个数字,它存储其索引。
请注意,数字中不存在的数字也不会出现在结构中,因此尝试对它们进行索引(
structure[digit_not_existing_in_number]
)将产生KeyError(这就是需要dict.get的原因)。但这很容易解决。
code00.py:
#!/usr/bin/env python
import sys
def o1_access_structure(n):
ret = {}
for i, e in enumerate(str(n)):
ret.setdefault(int(e), []).append(i)
return ret
def main(*argv):
ns = (
123455,
987385,
941726149,
)
for n in ns:
print("\n", n)
s = o1_access_structure(n)
for e in range(10):
print(" ", e, s.get(e))
if __name__ == "__main__":
print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
64 if sys.maxsize > 0x100000000 else 32, sys.platform))
rc = main(*sys.argv[1:])
print("\nDone.")
sys.exit(rc)
输出:
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q072713761]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" ./code00.py Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32 123455 0 None 1 [0] 2 [1] 3 [2] 4 [3] 5 [4, 5] 6 None 7 None 8 None 9 None 987385 0 None 1 None 2 None 3 [3] 4 None 5 [5] 6 None 7 [2] 8 [1, 4] 9 [0] 941726149 0 None 1 [2, 6] 2 [4] 3 None 4 [1, 7] 5 None 6 [5] 7 [3] 8 None 9 [0, 8] Done.
或者,如果您不关心数字索引,而只关心它们的存在/频率,您可以使用 [Python.Docs]: class collections.Counter([iterable-or-mapping]):
>>> from collections import Counter >>> >>> >>> c = Counter(int(e) for e in str(941726149)) >>> >>> for e in range(10): ... print(e, c[e]) ... 0 0 1 2 2 1 3 0 4 2 5 0 6 1 7 1 8 0 9 2