【问题标题】:How do I print a specific message if the user inputs the same string twice in Python?如果用户在 Python 中输入相同的字符串两次,我如何打印特定的消息?
【发布时间】:2020-11-28 09:42:03
【问题描述】:

我正在练习我的 Python 技能。我目前在第 4 周,坚持做一项特定的任务。如果用户在我的 self.songs 输入中两次输入相同的字符串,我想打印一条消息“你不能两次输入同一首歌曲。再试一次”。

我该怎么做?另外,有没有办法让用户在输入他们喜欢的歌曲时使用逗号而不是空格来分隔每个字符串?

  class User:
    def __init__(self):
        self.name = ''
        self.songs = ()
        self.movies = ()
        self.sports = ()

    def tops(self):
        self.name = input("What's you're full name?:")
        while True:
            self.songs = input('Hi ' + self.name + ', what is your top 5 favorite songs?:').split()
            if len(self.songs) > 5:
                print('You entered more than 5 songs. Try again')
            elif len(self.songs) < 5:
                print('You entered less than 5 songs. Try again')
            elif len(self.songs) == 5:
                for song in self.songs:
                    print(song)
                confirm_input = input('Do you confirm?')
                if confirm_input == 'Yes':
                    print(type(self.songs))
                    print(self.songs)
                    break
                elif confirm_input == 'No':
                    continue


quizUser = User()
quizUser.tops()

【问题讨论】:

  • confirm_input = input('Type Yes to confirm'),所以,用户知道输入 Yes 而不是通常的 y :)
  • 不要批评问题或答案。然而,有时采取不同的方法可能会很有用。如果您重构以循环询问标题直到 5,您可以通过签入列表轻松实现不重复。另外,您可以输入You Can't Always Get What You Want,目前这里是不可能的。

标签: python python-3.x


【解决方案1】:

您可以使用set 获取唯一元素,然后将其长度与答案长度进行比较

if len(set(self.songs)) != len(self.songs):
    print("You can't enter the same song twice. Try again")    
elif len(self.songs) > 5:
    print('You entered more than 5 songs. Try again')
elif len(self.songs) < 5:
    print('You entered less than 5 songs. Try again')
...

【讨论】:

    【解决方案2】:

    您可以使用set 获取不相同的元素,并使用!= 将其长度与普通列表进行比较。

    将此添加到您的代码中:

    elif len(set(self.songs)) != len(self.songs):
        print('You can\'t enter the same song twice. Try again')
    

    顺便说一句,\' 表示转义 '

    整个代码:

    class User:
            def __init__(self):
                self.name = ''
                self.songs = ()
                self.movies = ()
                self.sports = ()
        
            def tops(self):
                self.name = input("What's you're full name?:")
                while True:
                    self.songs = input('Hi ' + self.name + ', what is your top 5 favorite songs?:').split()
                    if len(self.songs) > 5:
                        print('You entered more than 5 songs. Try again')
                    elif len(self.songs) < 5:
                        print('You entered less than 5 songs. Try again')
                    elif len(self.songs) != len(set(self.songs)):
                        print('You can\'t enter the same song twice. Try again')
                    elif len(self.songs) == 5:
                        for song in self.songs:
                            print(song)
                        confirm_input = input('Do you confirm?')
                        if confirm_input == 'Yes':
                            print(type(self.songs))
                            print(self.songs)
                            break
                        elif confirm_input == 'No':
                            continue
        
        
    quizUser = User()
    quizUser.tops()
    

    【讨论】:

      【解决方案3】:

      您可以计算每个元素的出现次数,如果存在重复,则将 flag 设置为 1。
      以下是修改后的代码:

      class User:
          def __init__(self):
              self.name = ''
              self.songs = ()
              self.movies = ()
              self.sports = ()
      
          def tops(self):
              self.name = input("What's you're full name?:")
              while True:
                  ########################################
                  #Flag variable to check if the repetition occured
                  flag = 0
                  self.songs = input('Hi ' + self.name + ', what is your top 5 favorite songs?:').split()
                  #Loop over the songs
                  for i in self.songs:
                      #Check the count of each song, if greater than 1 set flag variable to 1 and empty songs.
                      if self.songs.count(i)>1:
                          print("You can't enter the same song twice. Try again")
                          self.songs = ()
                          flag = 1
                  #Check if flag is 1, if true exit the current iteration
                  if flag == 1:
                      continue
                  #######################################
                  if len(self.songs) > 5:
                      print('You entered more than 5 songs. Try again')
                  elif len(self.songs) < 5:
                      print('You entered less than 5 songs. Try again')
                  elif len(self.songs) == 5:
                      for song in self.songs:
                          print(song)
                      confirm_input = input('Do you confirm?')
                      if confirm_input == 'Yes':
                          print(type(self.songs))
                          print(self.songs)
                          break
                      elif confirm_input == 'No':
                          continue
      
      
      quizUser = User()
      quizUser.tops()
      

      【讨论】:

      • 你还有很多东西要学,还有其他更快、更简单的方法来检查重复、使用 collections.Counter 或像其他答案一样的“集合”;)
      • 同样在你的代码中flag = 1 可以直接替换为'continue'
      • @azro 如果使用 continue ,它将只退出 f​​or 循环并执行 for 循环下面的行。考虑到它们不应该被使用,因此没有使用任何库。目的是发展逻辑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2018-11-23
      • 1970-01-01
      相关资源
      最近更新 更多