【问题标题】:Returning True if a sequence appears in a list如果序列出现在列表中,则返回 True
【发布时间】:2015-07-06 18:30:43
【问题描述】:

我需要编写一个函数,它接受一个整数列表 nums,如果序列 1, 2, 3, .. 出现在列表中的某处,则返回 True。

我的做法:

def list123(nums):
    num = ""
    for i in nums:
        num += i
    if "1,2,3" in num:
        return True
    else:
        return False

它无法工作,指示:builtins.TypeError: Can't convert 'int' object to str implicitly

我也想知道是否有更简单的方法,而不是像我所做的那样将列表转换为字符串。

【问题讨论】:

    标签: list python-3.x boolean sequence


    【解决方案1】:

    您将在num += i 上收到错误,因为您正在尝试将1 添加到""。相反,请尝试以下方法:

    def list123(nums, desired=[1, 2, 3]):
        return str(desired)[1:-1] in str(nums)
    

    >>> list123([1, 2, 3, 4, 5])
    True
    >>> list123([1, 2, 4, 3, 5])
    False
    >>> list123([1, 2, 4, 3, 5], desired=[2, 4, 3])
    True
    >>> list123([5, 1, 2, 7, 3, 1, 2, 3])
    True
    >>> 
    

    【讨论】:

      【解决方案2】:
      def list123(nums):
          for i in range(0,len(nums)-1):
              if nums[i]==1:
                  if nums[i+1]==2:
                      if nums[i+2]==3:
                          return True
      
          return False       
      
      
      nums=[1, 2, 1, 3, 1, 2, 1]
      print(list123(nums))
      

      【讨论】:

      • 请在答案中添加一些细节,使其更有帮助
      【解决方案3】:
      def array123(nums):
        for i in range(0,len(nums)-2):
          if nums[i:i+3]==[1,2,3]:
            return True
        return False
      

      【讨论】:

        【解决方案4】:
        import re 
        def list123(nums):
            s = ''.join(str(x) for x in nums)
            if(re.search('123',s) != None):
                return True
            else:
                return False
        
        
        nums=[1,2,3,4,5]
        print(list123(nums))
        

        【讨论】:

          【解决方案5】:
          def array123(nums):
            num=''
            for i in nums:
              num += str(i)
            if num.count('1')>=1 and num.count('2')>=1 and num.count('3')>=1:
              return True
            else :
              return False
          

          【讨论】:

          • 请在您的答案中添加一些解释,以便其他人可以从中学习
          【解决方案6】:
          def arrayCheck(nums):
              if 1 in nums and 2 in nums and 3 in nums:
                  return "YES"
              else:
                  return "NO"
          

          有什么我遗漏的或者可以在没有 for 循环的情况下以这种方式编写的吗?

          【讨论】:

          • 嗨。欢迎来到 StackOverflow。不幸的是,您发布的代码的缩进无效,并且答案不正确,因为它只检查代码中是否存在 1,2 和 3,而 OP 想要检查序列1, 2, 3
          • 感谢您编辑缩进。不过,对于 OP 的问题,它仍然是一个不正确的解决方案。
          猜你喜欢
          • 1970-01-01
          • 2011-02-21
          • 2015-04-10
          • 2011-02-11
          • 1970-01-01
          • 1970-01-01
          • 2017-10-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多