列表中最小的ASCII值

-4 投票
3 回答
772 浏览
提问于 2025-04-18 05:29

有没有什么函数可以用来找出字符串中ASCII值最小的大写字母呢?

比如,给定这个输入字符串:

"Parker,Peter,Wayne,Bruce,Wilson,Wade"

# I want the function to return Parker,Peter \n Wayne,Bruce \n Wilson,Wade
# I know that I have to use the ord function in some sort of way, 
# and is there a way to accomplish this task using the min function?
# I have tried doing this function with a while loop and it works with 
# two names but not with any more.

def alphabetize(names):
 T = ''
 subscript = 0
 names = names.split(",")
 champ = ord(names[subscript][0])
 while len(names) > 0:
    if ord(names[subscript][0]) < champ:
        T += (names[subscript])
        T += " "
        T += (names[subscript + 1])
        T += "\n"
        del names[subscript]
        del names[subscript]
    elif ord(names[subscript][0]) > champ:
        T += (names[subscript])
        T += " "
        T += (names[subscript + 1])
        T += "\n"
        del names[subscript]
        del names[subscript]
    else:
        T += (names[subscript])
        T += " "
        T += (names[subscript + 1])
        T += "\n"
        del names[subscript]
        del names[subscript]
return T

print alphabetize("Kent,Clark,Wayne,Bruce")

提前感谢大家的帮助。

编辑:不允许使用sort()函数。

3 个回答

1
s = "Parker,Peter,Wayne,Bruce,Wilson,Wade"
min(x for x in s if ord('A') <= ord(x) <= ord('Z'))

或者

min(x for x in s if x in string.ascii_uppercase)
1

为什么不先把列表排序,然后取第一个元素呢?

比如说:

sorted(filter(lambda x: x.isupper(), list(str)))[0]
0

这是一种糟糕透顶的方法 - 但它确实能奏效:

def alphabetize(s, delimiter=","):
    values = s.split(delimiter)  # convert to a list
    result = []
    while values:
        # this is effectively select-sort - which is O(n**2) -
        # but even worse because deleting a list item is also
        # O(n), making it O(n**3) overall
        smallest = min(range(len(values)), key=values.__getitem__)
        result.append(values[smallest])
        del values[smallest]
    # rejoin the sorted items to a string
    return delimiter.join(result)

它的运行方式是这样的

>>> alphabetize("Parker,Peter,Wayne,Bruce,Wilson,Wade")
'Bruce,Parker,Peter,Wade,Wayne,Wilson'

撰写回答