python 字母数字排序[已关闭]

wkftcu5l  于 2022-12-10  发布在  Python
关注(0)|答案(3)|浏览(155)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

1小时前关闭。
Improve this question
我该怎么做?
编写一个满足以下要求的Python程序:
它提示用户输入六个字母数字字符(A-Z,0-9),用空格分隔。它按升序对用户输入进行排序,先输入字母,再输入数字。它将排序后的字符列表打印到屏幕上(用空格分隔)。它带有很好的注解。
示例:
如果程序的输入为8 G J 4 5 D,则输出为D G J 4 5 8
我写了一个程序,但是当只输入数字时,它会给予我一个错误。任何帮助都将不胜感激。

h4cxqtbf

h4cxqtbf1#

使用key排序,使十进制字符排在字母之前:

>>> s = "8 G J 4 5 D"
>>> print(*sorted(s.split(), key=lambda c: (c.isdecimal(), c)))
D G J 4 5 8
n3schb8v

n3schb8v2#

如果你想让你的代码快两倍,你可以使用一个查找表,我用了一行,但是它也可以被拆分。我打印这个来提供这个对象看起来像什么。对于数字我可以直接做一个列表,对于字母我会使用一个更紧凑的符号。

decode = {character: index for index, character in enumerate([chr(i) for i in range(ord("A"), ord("Z") + 1)] + ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])}
print(decode)

s = "8 G J 4 5 D"
print(*sorted(s.split(), key=lambda c: (c.isdecimal(), c)))
print(*sorted(s.split(), key = lambda c: decode[c]))

from timeit import repeat
loops = 500_000
count = 1
print(loops * min(repeat("sorted(s.split(), key=lambda c: (c.isdecimal(), c))", globals=globals(), repeat=loops, number=count)))
print(loops * min(repeat("sorted(s.split(), key = lambda c: decode[c])", globals=globals(), repeat=loops, number=count)))

输出量:

{'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25, '0': 26, '1': 27, '2': 28, '3': 29, '4': 30, '5': 31, '6': 32, '7': 33, '8': 34, '9': 35}
D G J 4 5 8
D G J 4 5 8
3.6460114642977715
2.3174798116087914

更多的想法?

5sxhfpxr

5sxhfpxr3#

# NOTE: This code is definitely not the most efficient.
import re  # Import the regex standard library to check the input later

input_ = input("Enter six alphanumeric characters, separated by spaces: ")  # Get the input

# Check if the input is six alphanumeric characters, separated by spaces.
# [A-Z0-9] in regex matches any character in the A-Z (capitalized) or 0-9 range
# ^ in regex matches the BEGINNING of the string
# $ in regex matches the END of the string
if not re.match(r"^[A-Z0-9] [A-Z0-9] [A-Z0-9] [A-Z0-9] [A-Z0-9] [A-Z0-9]$", input_):  # If the string does not match the pattern (that specifies for the aforesaid criteria)
  # Exit the program, printing "Invalid input"
  print("Invalid input")
  exit()

numbers_sorted = []  # Create a list that will later be populated with all the numbers in the input, sorted.
letters_sorted = []  # Create a list that will later be populated with all the Letters in the input, sorted.

# Loop through each character in the input.
# .split() splits the input into a list at every space (e.g. "a b c d e f".split() becomes ["a", "b", "c", "d", "e", "f"])
for character in input_.split(): 
  if character.isalpha():  # If the character is alphabetic
    # Sort the character into the `letters_sorted` list

    # Loop through the length of the list, such that the code in the loop is executed n times,
    # where n is the length of `letters_sorted`,
    # and the `index` variable starts at 0, and increases per iteration.
    for index in range(len(letters_sorted)):
      # ord() returns the 'character code' of a character (e.g. ord('a') returns 97, ord('b') returns 98)
      # If the `character` (from the outer for loop) is alphabetically preceeding the
      # character at position `index` of the `letters_sorted` list,
      if ord(letters_sorted[index]) > ord(character):
        letters_sorted.insert(index, character)  # Insert the `character` (from the outer loop) right before `index` of `letters_sorted`
        break  # Break from the loop as the character has been sorted into the list
    else:
      # If the character has not been sorted into the list
      # (if the character alphabetically succeeds every other character currently in `letters_sorted`)
      letters_sorted.append(character)  # Append the character to the very end of the list
  else:  # Otherwise (in this case, if the character is numeric)
    # Sort the character into the `numbers_sorted` list
    # See the comments above for sorting alphabetic characters
    # The only difference is not using the ord() function as we can directly compare numbers using less-than or greater-than
    # (also, we are using the `numbers_sorted` list now)
    for index in range(len(numbers_sorted)):
      if numbers_sorted[index] > character:
        numbers_sorted.insert(index, character)
        break
    else:
      numbers_sorted.append(character)

# Now, the lists are 'in order'.
# Finally, combine the lists to achieve a final list that contains letters sorted, then numbers sorted.
final_list = letters_sorted + numbers_sorted

# (Very) finally, convert the list to a string, separating each list entry by a space character:
final_string = " ".join(final_list)
# (Very very) finally, print the string:
print(final_string)

编辑:请选择上面的其他答案,所有的答案都比这一个要简洁得多

相关问题