【问题标题】:Checking items in a list to see if they are beside each other检查列表中的项目以查看它们是否彼此相邻
【发布时间】:2015-09-12 00:11:10
【问题描述】:

``所以我基本上是在尝试查看 python 列表中的两个项目是否彼此相邻。例如,如果我要查看数字 2 是否在此列表中的元素旁边。

example_List = [1,2,2,3,4]

它应该返回 True。到目前为止我有这个

def checkList(List1):
    for i in range(len(List1 - 1)):
        if list1[i] == 2 and list1[i+1] == 2:
            return True
    return False

我收到错误,错误:不支持的操作数类型为 -: 'list' 和 'int'

谢谢!

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    问题在于这部分:

    len(List1 - 1)
    

    你应该把它改成

    len(List1) - 1
    

    您应该对变量 List1 使用相同的大小写。 改变

    if list1[i] == 2 and list1[i+1] == 2:
    

    到:

    if List1[i] == 2 and List1[i+1] == 2:
    

    【讨论】:

      【解决方案2】:

      替换

      len(List1 - 1)
      

      len(List1) - 1
      

      【讨论】:

        【解决方案3】:

        这也是一个单行:

        def check( l,i ): return i in l and l[-1] != i and l[l.index(i)+1] == i
        

        诚然不是最好的,但我想还是比嵌套循环更好

        【讨论】:

          【解决方案4】:

          首先,你得到的错误是因为

          for i in range(len(List1 - 1)):
          

          这应该是

          for i in range(len(List1) - 1)):
          

          这是您可以使用的代码示例

          def checkList(List1):
              for i in range(len(List1) - 1)):
                  if List1(i) == List(i+1):
                      return True
          

          【讨论】:

            猜你喜欢
            • 2015-06-08
            • 1970-01-01
            • 1970-01-01
            • 2021-10-18
            • 1970-01-01
            • 2011-09-08
            • 2022-01-15
            • 2018-03-23
            • 1970-01-01
            相关资源
            最近更新 更多