简体   繁体   English

如何在嵌套列表中找到最后一次出现的项目?

[英]How to find the last occurrence of item in nested list?

I have a randomly generated list with a similar format我有一个随机生成的具有类似格式的列表

data = [['item','A'],['colour',1],['colour',3],['item','D']]

I want to find where 'colour' last occurred and print the number associated with it我想找到“颜色”最后出现的位置并打印与之关联的数字

for item in data:
    if item[-1] == 'colour':
        print(item[1])

this loop I have now prints nothing这个循环我现在什么都不打印

You can change it to:您可以将其更改为:

for item in data[::-1]:
    if item[0] == 'colour':
        print(item[1])
        break

You have to change three things.你必须改变三件事。

  • The first loop iterates from last to first item [::-1] (You can also use .reverse() reverse )第一个循环从最后一项迭代到第一项[::-1] (您也可以使用.reverse() reverse
  • and checks if the first item item[0] in the sublist is "colour" .并检查子列表中的第一项item[0]是否为"colour" (Your [-1] checks the last item in the sublist, that are the numbers in your case) (您的[-1]检查子列表中的最后一项,即您的案例中的数字)
  • If the first "colour" is found, the loop is break ed.如果找到第一个"colour" ,则循环break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM