在嵌套列表中查找元素索引

时间:2020-04-17 00:18:33

标签: python list

试图在嵌套循环中找到元素的元素索引。

<div class="container"> 
  <figure class="image-container">
    <img src="https://images.unsplash.com/photo-1586889720013-37a246a378d3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="" class="img">
  </figure>
  
    <figure class="image-container">
    <img src="https://images.unsplash.com/photo-1586835319938-307d4746d12d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" alt="" class="img">
  </figure>
  

<figure class="image-container">
    <img src="https://images.unsplash.com/photo-1562873656-65edf09f1b9b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=701&q=80" alt="" class="img">
</figure>



</div>

但是每次我运行代码时,它告诉我Y不在我的列表中

2 个答案:

答案 0 :(得分:3)

您不需要嵌套循环。您可以遍历各行并在该行上调用index()。您可以捕捉到Y不在列表中时将发生的错误。这是询问forgiveness instead of permission的Python风格:

for row in table:
    try:
        print(row.index("Y"))
    except ValueError:
        pass

如果您只想知道表中是否是“ Y”,则可以使用any()

any('Y' in row for row in table)
# True

答案 1 :(得分:1)

您的内循环没有任何意义; index已经涵盖了整个列表;为什么需要做3次?

如果该项目没有出现,您将得到一个错误。代替

for i in range(len(table)):
    if 'Y' in table[i]:
        print(i, table[i].index('Y'))

对于每一行,请检查是否显示Y。如果是这样,则在出现的行和列号上进行打印。