【问题标题】:alphabetically sorting multiple strings按字母顺序排序多个字符串
【发布时间】:2021-04-10 04:09:01
【问题描述】:

我尝试编写的代码必须包含来自用户的提示和三个单独的字符串。当我要求用户在同一提示中输入 3 个单词时,我能够使排序功能起作用,但是当我将输入分开时,排序功能不起作用。我对编码非常陌生(第一周),所以如果不清楚,我深表歉意。

我应该编写一系列 Python 语句来提示用户输入三个字符串。然后,使用 'if' 语句,按字母顺序打印它们。

这是我到目前为止的代码: 有人有什么建议吗?

谢谢!

word1 = input(str("Please enter a word of your choice:"))
word2 = input(str("please enter another word, but make sure the word does not start with the same letter:"))
word3 = input(str("Awesome! Ok, finally, enter one last word, again making sure not to use the same letter:"))
    
if (word1 == word2):
    print("The words are the same")
else:
    print("Nicely done, you read directions well!")
       
print("The words in alphabetical order are..")

接下来是什么?我在任何地方都找不到此信息。

【问题讨论】:

  • 在您的表达式str("Please...") 中,str 是多余的,因为它们已经是字符串。与您的问题无关,但正如您所说的,您是初学者,我想您可能想知道。

标签: python-3.x string if-statement input alphabetical


【解决方案1】:

您需要比较字符串并给出比较结果,然后执行一个操作。使用this resource中的字符串比较比较字符串和this post中的算法,可以对三个字符串进行排序。

word1 = input(str("Please enter a word of your choice:"))
word2 = input(str("please enter another word, but make sure the word does not start with the same letter:"))
word3 = input(str("Awesome! Ok, finally, enter one last word, again making sure not to use the same letter:"))

if (word1 == word2):
    print("The words are the same")
else:
    print("Nicely done, you read directions well!")

print("The words in alphabetical order are..")

if(word1>word3):
  tmp = word1
  word1 = word3
  word3 = tmp

if(word1>word2):
  tmp = word1
  word1 = word2
  word2 = tmp

if(word2>word3):
  tmp = word2
  word2 = word3
  word3 = tmp

print(word1)
print(word2)
print(word3)

【讨论】:

    【解决方案2】:

    正如另一个回复中提到的,使用“if”语句肯定会解决这个问题。但是,如果您不局限于“if”语句,并且为了了解更多有关 Python 的信息,使用列表可以以一种简洁而简单的方式解决您的问题。请看下面的代码:

    word1 = input(str("Please enter a word of your choice:"))
    word2 = input(str("please enter another word, but make sure the word does not start with the same letter:"))
    word3 = input(str("Awesome! Ok, finally, enter one last word, again making sure not to use the same letter:"))
        
    if (word1 == word2 or word1 == word3 or word2 == word3):
        print("The words are the same")
    else:
        print("Nicely done, you read directions well!")
           
    word_list = [word1, word2, word3]
    word_list.sort()
    
    print("The words in alphabetical order are..")
    for word in word_list:
        print(word)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      相关资源
      最近更新 更多