Python - 按字母顺序排列单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13809542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:40:46  来源:igfitidea点击:

Python - arranging words in alphabetical order

pythonlistrangealphabetical

提问by CrashZer0

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.

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

回答by inspectorG4dget

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

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

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'

Or, sort it reversed:

或者,将其反向排序:

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

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

如果您希望这与大小写无关,请务必先调用str.lower()您的words:

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

回答by adarsh

Use the sort()method.

使用sort()方法。

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

Output will be,

输出将是,

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

In case you want the last, you can use the max()method.

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

回答by Fyre

In python the method sort() sorts all strings alphabetically so you can use that function.

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

You can make a list of all your words and then :

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

  listName.sort()

This would result a alphabetically sorted list.

这将产生按字母顺序排序的列表。

回答by Akavall

If you have a mix of capitalized words and lowercase words you could do this:

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

from string import capwords     

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

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

answer = words[-1]

Result:

结果:

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

回答by James Waldby - jwpat7

As noted in a previous answer, string comparisons are lexical by default, so min()and max()can be used. To handle both upper- and lower-cased words, one can specify key=str.lower. For example:

正如在前面的回答指出,比较字符串默认词汇,所以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

回答by Shubham Kundu

Just use the following:

只需使用以下内容:

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

回答by seeker

This would be how I would do it.

这就是我要做的。

  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 sentencestring. I use the term "word" here loosely as the method has no conception of "word", it merely separates the sentencestring 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 sortedfunction:The sorted function returns an alphabetically ordered version of the split_sentencelist.

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

    print(sorted_sentence[-1])
    
  1. 定义字符串:为了参数起见,让我们说字符串已经被预定义。

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

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

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

    print(sorted_sentence[-1])