[英]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.你必须改变三件事。
[::-1]
(You can also use .reverse()
reverse )[::-1]
(您也可以使用.reverse()
reverse )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]
检查子列表中的最后一项,即您的案例中的数字)"colour"
is found, the loop is break
ed."colour"
,则循环break
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.