Python - 将单词按字母顺序排列

10

该程序必须打印出8个元素中按字母顺序最后一个名称。 可以通过代码以任何方式输入名称/单词。 我认为我应该在此处使用列表和 in range()。我有一个想法,即将输入名称的第一个/第二个/第三个/...个字母与先前名称的字母进行比较,然后将其放在列表末尾或前面(取决于比较结果),然后重复这个过程直到下一个名称。最后,程序将打印出列表的最后一个成员。


这是一道必须按特定方式完成的练习吗?还是可以像已经给出的答案建议那样使用sortmax - Stuart
我现在不想写一个完整的答案,但你应该记住,推荐使用 maxsort 的答案不一定会正确处理大小写,因为它们按照字符的数字值进行排序(所以 A < B,但 a > B)。 - Brendan Long
你可以随时使用大写或小写。 - adarsh
以下是如何使用特定语言环境设置正确地按字母顺序排序的示例:https://dev59.com/hnVD5IYBdhLWcg3wQZUg#36156 - Brendan Long
7个回答

9

Python的字符串比较默认是按字典顺序进行的,所以您应该能够直接调用max函数:

In [15]: sentence
Out[15]: ['this', 'is', 'a', 'sentence']
In [16]: max(sentence)
Out[16]: 'this'

当然,如果你想手动完成此任务:
In [16]: sentence
Out[16]: ['this', 'is', 'a', 'sentence']

In [17]: answer = ''

In [18]: for word in sentence:
   ....:     if word > answer:
   ....:         answer = word
   ....:         

In [19]: print answer
this

或者你可以对你的句子进行排序:

In [20]: sentence
Out[20]: ['this', 'is', 'a', 'sentence']

In [21]: sorted(sentence)[-1]
Out[21]: 'this'

或者,反向排序:

In [25]: sentence
Out[25]: ['this', 'is', 'a', 'sentence']

In [26]: sorted(sentence, reverse=True)[0]
Out[26]: 'this'

但是如果你想完全手动(这很痛苦):
def compare(s1, s2):
    for i,j in zip(s1, s2):
        if ord(i)<ord(j):
            return -1
        elif ord(i)>ord(j):
            return 1
    if len(s1)<len(s2):
        return -1
    elif len(s1)>len(s2):
        return 1
    else return 0

answer = sentence[0]
for word in sentence[1:]:
    if compare(answer, word) == -1:
        answer = word

# answer now contains the biggest word in your sentence

如果您希望不受大小写影响,务必先在您的单词上调用str.lower()
sentence = [word.lower() for word in sentence] # do this before running any of the above algorithms

4
使用sort()方法。
strings = ['c', 'b', 'a']
strings.sort()
print strings

输出结果将是:
['a', 'b', 'c']

如果您想要最后一个,您可以使用max()方法。


3

如前面的回答所述,默认情况下字符串比较是按字典顺序进行的,因此可以使用min()max()。为了处理大写和小写单词,可以指定key=str.lower。例如:

s=['This', 'used', 'to', 'be', 'a', 'Whopping', 'Great', 'sentence']
print min(s), min(s, key=str.lower)
# Great a

print max(s), max(s, key=str.lower)
# used Whopping

在所有答案中,这是最简明扼要的答案,并直接回答了OP的问题并解释了其原理。但是,如果你想处理大小写混合的带有非ASCII字母的单词,你可能需要添加一些关于locale.collate的提及。 - abarnert

2
如果您同时有大写和小写字母的混合词汇,可以采用以下方式:
from string import capwords     

words = ['bear', 'Apple', 'Zebra','horse']

words.sort(key = lambda k : k.lower())

answer = words[-1]

结果:

>>> answer
'Zebra'
>>> words
['Apple', 'bear', 'horse', 'Zebra']

为什么要使用 string.capwords(s) 而不是只用 s.lower()s.upper() - abarnert
@abarnert,没有真正的原因。我看到s.lower()s.upper()的优点是您不需要导入任何模块(string),您知道其他优点吗? - Akavall
比较s.lower()是进行不区分大小写(ASCII)比较的典型方式;使用一个如此鲜为人知以至于他们选择不将其添加为str方法的函数意味着人们必须思考代码,而不是立即认识到它的作用(自动重构工具根本无法识别它)。你听说过“TOOWTDI”吗?还有一些小优点——lower也更有可能在不同的Python实现上进行优化,更容易阅读(一个单词告诉你它做什么,而不是两个单词中的一个与此无关),等等。 - abarnert

1
这就是我会做的方式。
  1. Define the string: For arguments sake let us say that the string is already predefined.

    sentence = "This is the sentence that I need sorted"
    
  2. Use the split() method: The split() method returns a list of "words" from the sentence string. I use the term "word" here loosely as the method has no conception of "word", it merely separates the sentence string into a list by parsing it for characters delimited by whitespace and outputs these characters as discrete items in a list. This list is not yet alphabetically ordered.

    split_sentence = sentence.split()
    
  3. Use the sorted function: The sorted function returns an alphabetically ordered version of the split_sentence list.

     sorted_sentence = sorted(split_sentence)
    
  4. Print the last element in the list:

    print(sorted_sentence[-1])
    

0
在Python中,sort()方法按字母顺序对所有字符串进行排序,因此您可以使用该函数。
您可以制作一个包含所有单词的列表,然后:
  listName.sort()

这将导致一个按字母顺序排序的列表。


0

只需使用以下内容:

max(sentence.lower().split())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接