我试图排序一个包含二进制字符串的字典,但它似乎不能正确排序。我使用的代码如下:
dict1 = {"5": "101", "1": "001", "17": "10001", "3" : "11"}
print("Unsorted dict:",dict1)
sorted_tuples = sorted(dict1.items(), key=lambda item: item[1])
print("Sorted tuples:",sorted_tuples)
sorted_dict = {k: v for k, v in sorted_tuples}
print("Sorted dict:",sorted_dict)
我期望输出是:
Unsorted dict: {'5': '101', '1': '001', '17': '10001', '3': '11'}
Sorted tuples: [('3', '11'), ('1', '001'), ('5', '101'), ('17', '10001')]
Sorted dict: {'3': '11', '1': '001', '5': '101', '17': '10001'}
我认为11会出现在001之前的原因是11是两个字符,001是三个字符。我假设,这将继续下去,并且五个字符的字符串将排在两个字符的字符串之后。
但是,我得到的输出是:Unsorted dict: {'5': '101', '1': '001', '17': '10001', '3': '11'}
Sorted tuples: [('1', '001'), ('17', '10001'), ('5', '101'), ('3', '11')]
Sorted dict: {'1': '001', '17': '10001', '5': '101', '3': '11'}
每个值的键都是象征性的,因此更容易显示。重要的部分是值——它们是我想要排序的。
有什么建议吗?
试试这个
dict1 = {"5": "101", "1": "001", "17": "10001", "3" : "11"}
print("Unsorted dict:",dict1)
sorted_tuples = sorted(dict1.items(), key=lambda item: (len(item[1]),int(item[1])))
# you can also change int(item[1]) to int(item[0]) or item[1](for binary string as @Tomerikoo say.)
print("Sorted tuples:",sorted_tuples)
sorted_dict = {k: v for k, v in sorted_tuples}
print("Sorted dict:",sorted_dict)
输出Unsorted dict: {'5': '101', '1': '001', '17': '10001', '3': '11'}
Sorted tuples: [('3', '11'), ('1', '001'), ('5', '101'), ('17', '10001')]
Sorted dict: {'3': '11', '1': '001', '5': '101', '17': '10001'}
解释。
- 正如您所说的
11 would come before 001 is that 11 is two charcters and 001 is three.
这里您需要使用len(item[1])
按长度对元素进行排序。