将此与@jamylak 的答案进行对比,后者只为您提供 50 个键而无需额外控制。在这里您可以获得最小的 50 个键
>>> d = dict.fromkeys(range(-50, 50))
>>> import heapq
>>> heapq.nsmallest(50, d)
[-50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
您可以通过提供不同的标准来key=func
订购heapq.nsmallest
>>> heapq.nsmallest(50, d, key=str)
[-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -3, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -4, -40, -41, -42, -43, -44, -45, -46, -47, -48, -49, -5, -50, -6, -7, -8, -9]