【问题标题】:How to write a conditional statement that refers to a certain index in a list?如何编写引用列表中某个索引的条件语句?
【发布时间】:2014-07-07 20:31:28
【问题描述】:

我想编写一个语句来检查某个数字是否在我的列表的索引中,如果是,则执行一些任务,然后从列表中弹出这个项目,但我似乎找不到任何可靠的信息这个具体的任务。下面的代码不起作用,但这本质上是我想要做的。我相信错误在第 6 行(if item[2] ==3:):

TypeError: 'int' object has no attribute '__getitem__'

示例代码:

x = [1,2,3]

for item in self.x:
      if item[2] == 3:
        print "working"
      else:
        print "not working"

【问题讨论】:

  • item 是您列表的元素之一,所以 1,然后是 2,然后是 3。我不确定我是否遵循您想在这里做的事情;你想看看item == 3吗?
  • 是的,我想查看我在列表中指定的索引,看看在这种情况下它是否等于索引 2 处的某个项目。
  • 应该是self.x[2],而不是item[2],但循环测试毫无意义。
  • 总是显示完整的错误信息。

标签: python list python-2.7 for-loop


【解决方案1】:

使用 list.index() 在列表中查找项目,做你的工作然后删除索引项目:

x = [1,2,3]
try:
    index = x.index(3)    # find 3 or raise exception
    print "found"         # do your work
    del x[index]          # 'pop' (well, delete) 3
except ValueError:
    print "not found"

【讨论】:

    【解决方案2】:

    您的循环正在遍历x 中的每个项目。每个整数都通过item 引用。因此,您正在检查:if 3[2] == 3,这是一个类型错误。

    您可以在 for 循环之外进行检查:

    if x[2] == 3:
        print "working"
    else:
        print "not working"
    

    【讨论】:

      【解决方案3】:

      item 是存储来自x 的元素的变量;你不需要下标任何东西。

      x = [1,2,3]
      
      for item in self.x:
            if item == 3:
              print "working"
            else:
              print "not working"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-13
        • 2012-04-03
        • 1970-01-01
        • 2019-10-09
        • 2017-02-03
        • 1970-01-01
        • 2016-03-26
        • 2018-12-17
        相关资源
        最近更新 更多