![](/img/trans.png)
[英]Counting Numbers, Uppercase Letters, Lowercase Letters and Spaces with own Function
[英]sorting keys of a dictionary with lowercase letters, uppercase letters and numbers
我想先按數字然后小寫字母然后大寫字母對字典的鍵進行排序,然后將其返回到字典中並使用正確的鍵值。 我想出了這個,但在我看來這太長了。 (board 是您要排序的給定字典)board 示例:
board = {
(3, 4) : 0,
("a", 4) : 0,
(1, 3) : 0,
("X", 5) : 5,
("X", 1) : 1
}
我的問題是是否可以縮短代碼。
x = []
y = []
for k in dict.keys(board):
if str(k[0]).islower():
list.append(x, (k, board[k]))
for k in dict.keys(board):
if k[0] == "X":
list.append(y, (k, board[k]))
for k in range(0, len(x)):
del board[x[k][0]]
for k in range(0, len(y)):
del board[y[k][0]]
x = sorted(x)
y = sorted(y)
for k in range(0, len(x)):
board[x[k][0]] = x[k][1]
for k in range(0, len(y)):
board[y[k][0]] = y[k][1]
按照所需順序進行排序,但基於關鍵元組。
因此 ('X', 1) 應該在 ('X', 5) 之前,因為第一個元素是相等的,所以取決於第二個元素。
排序例程
def sort_dict(d):
def ordering(i):
"""Create ordering so that numbers are before strings
lowercase strings are before upper case strings"""
return ([isinstance(i, int), isinstance(i, str) and i.islower(), isinstance(i, str) and i.isupper()].index(True), i)
# By applying ordering to all elements of key, we create a new tuple
# which allows us to compare
return dict(sorted(d.items(), key=lambda kv: tuple(map(ordering, kv[0]))))
測試
board = {(3,4):0,("a",4):0,(1,3):0,("X",5):5,("X",1):1}
print(sort_dict(board))
輸出
{(1, 3): 0, (3, 4): 0, ('a', 4): 0, ('X', 1): 1, ('X', 5): 5}
你也許可以做這樣的事情:
result = {}
for x in sorted(filter(lambda x: type(x[0]) == int, board.keys())):
result[x] = board[x]
for x in sorted(filter(lambda x: type(x[0]) == str, board.keys()), key=lambda x: x[0].islower(), reverse=True):
result[x] = board[x]
>>> result
{(1, 3): 0, (3, 4): 0, ('a', 4): 0, ('X', 5): 5, ('X', 1): 1}
另外,以防萬一,如果您想在小寫字母之前使用大寫字母並且數字只有 1 位長,那么您可以使用ord對它們進行排序
>>>sorted(board.keys(), key=lambda x: ord(str(x[0])) if type(x[0]) == int else ord(x[0]))
[(1, 3), (3, 4), ('X', 5), ('X', 1), ('a', 4)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.