【问题标题】:Why this method doesn't not work for this question?为什么这种方法不适用于这个问题?
【发布时间】:2021-01-03 14:00:13
【问题描述】:

问题:给定一个整数列表,如果该数组在某处的某个 3 旁边包含一个 3,则返回 True。

经验: has_33([1, 3, 3]) → 真

我的代码:

def has_33(nums):
     for items in nums:
        if items == 3:
            if nums[nums.index(items)+1] == 3:
                return True
           
            else:
                continue
    
    return False

使用此代码,我无法得到我想要的答案。我现在得到的答案是: has_33([1, 3, 1, 3]) → 假 has_33([3, 1, 3]) → 假 has_33([3, 1, 3, 3]) → False #连“3”旁边也是“3”。

【问题讨论】:

  • 至于具体为什么这不起作用。请阅读indexdocumentation 及其作用。应该很清楚为什么这不起作用

标签: python-3.x


【解决方案1】:

.index() 返回项目的第一个找到的索引。在[3,1,3,3]的情况下,1不等于3,所以循环继续。

您需要不同的逻辑,因为如果您输入了 [1,2,3],例如,您的前 3 个在列表中的最后一个,您会得到一个 IndexError

一种可能的方式:Iterating over every two elements in a list

【讨论】:

    【解决方案2】:

    index() 方法为您提供项目第一次出现的索引,使用enumerate 是更有效的方法。 check out here

    def has_33(arr):
        for index, item in enumerate(arr[:-1]):
            if item == 3 and arr[index+1] == 3:
                return True
    
        return False
    

    【讨论】:

    • 如果你解释了为什么 OP 的代码不起作用,以及你是如何修复它的,那会更有用。
    【解决方案3】:

    目前,您正在搜索数字列表中第一次出现的 3,即 nums.index。但在您的示例中,这将是列表中的前 3 个,而不是第三个。这段代码会做你想做的事,它适用于任何数字,通过给它第二个可选参数:

    def has_xx(nums, x=3):
        for index, num in enumerate(nums):
            if num == x:
                try:
                    if nums[index + 1] == x:
                        return True
                   
                    else:
                        continue
                except IndexError:
                    continue
        return False
    

    工作如下:

    >>> has_xx([1, 2, 3, 3, 5])
    True
    >>> has_xx([1, 2, 3, 4, 4, 3])
    False
    >>> has_xx([1, 2, 3, 4, 4, 3], x=4)
    True
    >>> has_xx([1, 2, 3, 4, 4, 3], x=3)
    False
    

    【讨论】:

      【解决方案4】:

      .index 为您提供该值第一次出现的索引

      >>> lst=[3,1,3,3]
      >>> lst.index(3)
      0
      >>>
      

      你可以给它第二个参数start,这样它就会给你从那里开始计数的值的位置

      >>> lst.index(3,1)
      2
      >>> lst.index(3,0)
      0
      >>> lst.index(3,2)
      2
      >>> lst.index(3,3)
      3
      >>> 
      

      但我会使用 zip 将元素与下一个元素配对,然后查看 (3, 3) 是否存在

      >>> list(zip(lst, lst[1:]))
      [(3, 1), (1, 3), (3, 3)]
      >>> any((3, 3) == pair for pair in zip(lst, lst[1:]))
      True
      >>> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多