Python - 按字母顺序排列单词



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

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() word

sentence = [word.lower() for word in sentence] # do this before running any of the above algorithms

使用 sort() 方法。

strings = ['c', 'b', 'a']
strings.sort()
print strings

输出将是,

['a', 'b', 'c']

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

如前面的答案所述,默认情况下字符串比较是词法的,因此可以使用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

如果你混合了大写和小写的单词,你可以这样做:

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

这就是我会这样做的方式。

  1. 定义字符串:为了参数起见,我们假设字符串已经预定义。

    sentence = "This is the sentence that I need sorted"
    
  2. 使用 split() 方法:split() 方法sentence字符串返回"单词"列表。我在这里松散地使用术语"word",因为该方法没有"word"的概念,它只是通过解析由空格分隔的字符将sentence字符串分隔到列表中,并将这些字符输出为列表中的离散项目。此列表尚未按字母顺序排列。

    split_sentence = sentence.split()
    
  3. 使用 sorted 函数:排序的函数返回按字母顺序排列的split_sentence列表版本。

     sorted_sentence = sorted(split_sentence)
    
  4. 打印列表中的最后一个元素:

    print(sorted_sentence[-1])
    

在python中,sort()方法按字母顺序对所有字符串进行排序,因此您可以使用该函数。

您可以列出所有单词,然后:

  listName.sort()

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

只需使用以下方法:

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

最新更新