【问题标题】:Python - arranging words in alphabetical orderPython - 按字母顺序排列单词
【发布时间】:2012-11-28 08:57:52
【问题描述】:

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

【问题讨论】:

  • 这是您必须以特定方式进行的练习,还是您可以按照已经给出的答案中的建议使用sortmax
  • 我现在不想写一个完整的答案,但你应该记住,推荐 maxsort 的答案不一定正确处理大写,因为它们按the numeric value of a character(所以A B,但是a > B)。
  • 为此,您始终可以使用上或下
  • 以下是如何使用特定区域设置正确按字母顺序排序的示例:stackoverflow.com/a/36156/212555

标签: python list range alphabetical


【解决方案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])
    

【讨论】:

    【解决方案2】:

    只需使用以下内容:

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

    【讨论】:

      【解决方案3】:

      如果您混合使用大写单词和小写单词,您可以这样做:

      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,没有真正的原因。我看到s.lower()s.upper() 的优点是不需要导入任何模块(string),您知道其他优点吗?
      • 嗯,比较 s.lower() 是进行不区分大小写 (ASCII) 比较的典型方式;使用一个鲜为人知的函数,以至于他们选择不将其添加为 str 方法意味着人们将不得不考虑代码而不是立即识别它的作用(并且自动重构工具根本无法识别它)。你听说过“TOOWTDI”,对吧?还有一些小优点——lower 也更有可能在不同的 Python 实现上进行优化,更容易阅读(一个词告诉你它做了什么,而不是两个,其中一个是不相关的)等等。
      【解决方案4】:

      如上一个答案所述,字符串比较默认是词法的,因此可以使用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
      

      【讨论】:

      • +1。在所有答案中,这是最简洁的,它直接回答了 OP 的问题并解释了它为什么起作用。但是,如果您想处理包含非 ASCII 字母的混合大小写单词,则可能需要提及 locale.collate
      【解决方案5】:

      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
      

      如果您希望这与大小写无关,请务必先在您的words 上致电str.lower()

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

      【讨论】:

        【解决方案6】:

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

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

          listName.sort()
        

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

        【讨论】:

          【解决方案7】:

          使用sort() 方法。

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

          输出将是,

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-07-13
            • 1970-01-01
            • 2015-12-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-09-24
            相关资源
            最近更新 更多