列表中最小的ASCII值

时间:2014-05-06 00:13:30

标签: python while-loop ascii

是否有一个函数可以用来查找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 个答案:

答案 0 :(得分:1)

为什么不对列表进行排序然后采用索引0?

e.g。

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

答案 1 :(得分: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)

答案 2 :(得分: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'