Python-按字母顺序排列单词 [英] Python - arranging words in alphabetical order

查看:1361
本文介绍了Python-按字母顺序排列单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The program must print the name which is alphabetically the last one out of 8 elements. The names/words can be inputted in any way through code. I think I should be using lists and in range() here. I had an idea of comparing the first/second/third/... letter of the input name with the letters of the previous one and then putting it at the end of the list or in front of the previous one (depending on the comparison), and then repeating that for the next name. At the end the program would print the last member of the list.

推荐答案

默认情况下,Python的字符串比较是词法比较的,因此您应该能够调用max并摆脱它:

Python's string comparisons are lexical by default, so you should be able to call max and get away with it:

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

当然,如果要手动执行此操作:

Of course, if you want to do this manually:

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

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

Or you can sort your sentence:

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'

但是,如果您要完全手动操作(这很痛苦):

But if you want to fully manual (which is so painful):

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

如果您不希望使用大写字母,请务必先word调用str.lower():

If you want this to be agnostic of capitalization, be sure to call str.lower() on your words first:

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

这篇关于Python-按字母顺序排列单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆