gpt4 book ai didi

python - 按键对字典进行排序(键是带有数字的字符串)

转载 作者:行者123 更新时间:2023-12-04 07:19:41 25 4
gpt4 key购买 nike

:尝试按键对字典进行排序

: 按键有数字

尝试这样做

def DictSortedKey(dictionary):
Dict = {}
for key in sorted(dictionary):
Dict[key] = dictionary[key]

return Dict


a = {"A 1": "<class-id>", "A 2": "<class-id>", "A 11": "<class-id>"}

a = DictSortedKey(a)

print(a)

但它返回 {'A 1': '<class-id>', 'A 11': '<class-id>', 'A 2': '<class-id>'}

而不是 {'A 1': '<class-id>', 'A 2': '<class-id>', 'A 11': '<class-id>'}

.

如何让它返回

{'A 1': '<class-id>', 'A 2': '<class-id>', 'A 11': '<class-id>'}

而不是 {'A 1': '<class-id>', 'A 2': '<class-id>', 'A 11': '<class-id>'}

最佳答案

更改键的排序方式。不是按其字符串值排序,而是按其整数值排序。在这里,我们不是按字符串 "A 11" 排序,而是按元组 ("A", 11) 排序,因此我们将首先按字母和然后按整数值(字典顺序记录为 here )。

def DictSortedKey(dictionary):
Dict = {}

for key in sorted(dictionary, key=lambda key: (key.split()[0], int(key.split()[1]))): # Sort by a tuple of (str, int)
Dict[key] = dictionary[key]

return Dict


a = {"A 1": "<class-id>", "A 3012323187": "<class-id>", "A 2": "<class-id>", "C 23": "<class-id>", "A 11": "<class-id>", "C 10001": "<class-id>", "B 4": "<class-id>"}

a = DictSortedKey(a)

print(a)

输出:

{'A 1': '<class-id>', 'A 2': '<class-id>', 'A 11': '<class-id>', 'A 3012323187': '<class-id>', 'B 4': '<class-id>', 'C 23': '<class-id>', 'C 10001': '<class-id>'}

简单来说,按字符串排序就像同义词库中通常的单词排序一样,其中 "atmosphere" 出现在 "bow" 之前,就像 "30123231 " 会出现在 "4" 之前。

numbers = ["1", "30123231" "87", "101", "3444", "2", "4", "3"]

print("Sort by string value:", sorted(numbers))
print("Sort by integer value:", sorted(numbers, key=lambda num: int(num)))
print("Sort by integer value:", sorted(map(int, numbers)))

输出:

Sort by string value: ['1', '101', '2', '3', '3012323187', '3444', '4']
Sort by integer value: ['1', '2', '3', '4', '101', '3444', '3012323187']
Sort by integer value: [1, 2, 3, 4, 101, 3444, 3012323187]

关于python - 按键对字典进行排序(键是带有数字的字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68587300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com