简体   繁体   English

用小写字母、大写字母和数字对字典的键进行排序

[英]sorting keys of a dictionary with lowercase letters, uppercase letters and numbers

I want to sort the keys of a dictionary first by numbers then lowercase letters and then uppercase letter and return it back in a dictionary with the correct value for the key.我想先按数字然后小写字母然后大写字母对字典的键进行排序,然后将其返回到字典中并使用正确的键值。 I came up with this, but in my opinion this is too long.我想出了这个,但在我看来这太长了。 (board is the given dictionary you want to sort) board example : (board 是您要排序的给定字典)board 示例:

board = {
  (3, 4) : 0,
  ("a", 4) : 0,
  (1, 3)  :  0,
  ("X", 5) : 5,
  ("X", 1) : 1
}

My question is if it is possible to shorten the code.我的问题是是否可以缩短代码。

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]

Following sort based in desired order but based upon the key tuple.按照所需顺序进行排序,但基于关键元组。

Thus ('X', 1) should be before ('X', 5) because first elements are equal so depends on second element.因此 ('X', 1) 应该在 ('X', 5) 之前,因为第一个元素是相等的,所以取决于第二个元素。

Sort Routine排序例程

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]))))

Test测试

board =  {(3,4):0,("a",4):0,(1,3):0,("X",5):5,("X",1):1}
print(sort_dict(board))

Output输出

{(1, 3): 0, (3, 4): 0, ('a', 4): 0, ('X', 1): 1, ('X', 5): 5}

You can maybe do something like this:你也许可以做这样的事情:

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}

Also, just in case if you wanted to have uppercase letters before lowercase and if the numbers were only 1 digit long then you could have used ord to sort them另外,以防万一,如果您想在小写字母之前使用大写字母并且数字只有 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.

相关问题 用自己的 Function 计数数字、大写字母、小写字母和空格 - Counting Numbers, Uppercase Letters, Lowercase Letters and Spaces with own Function Python - 检查数字,大写,小写字母和特殊字符的输入 - Python - Checking an input for numbers, uppercase, lowercase letters and special characters 在python中排序小写字母 - Sorting lowercase letters in python 不将 python 中的字母转换为大写和小写 - Not converting letters to uppercase and lowercase in python 小写和大写字母之前和之后 - Before and after lowercase and uppercase letters 交替添加大写和小写字母? - Alternately add uppercase and lowercase letters? 将小写字母更改为:数字00-25,将大写字母更改为:数字26-51 - Change lowercase letters to: numbers 00-25, and uppercase letters to: numbers 26-51 按由数字和字母组成的键对字典进行排序 - Sorting a dict by keys consisting of numbers and letters 我可以识别小写和大写字母并将它们放入字典中。 我需要将大写和小写值连接在一起 - I can identify lowercase and uppercase letters and put them in a dictionary. I need to join the uppercase and lowercase values together 将一些小写字母更改为字符串中的大写 - change some lowercase letters to uppercase in string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM