[英]How do I find index of list in nested list in python
I've got a list which I want to find the index of a nested list using one of the tuples (16, 29, 32, 40) like a dictionary. 我有一个列表,我想使用像字典一样的元组(16、29、32、40)之一找到嵌套列表的索引。
list2 = [[(4, 8, 16, 29), 1, '[#1]:'], [(16, 29, 32, 40), 1, '[#2]:']]
item_position = list2.index([(16, 29, 32, 40)]) #Error here!
print("item_position", item_position)
Output error:
item_position = list2.index([(16, 29, 32, 40)])
ValueError: [(16, 29, 32, 40)] is not in list
When the list is: 当列表是:
list2 = [[(4, 8, 16, 29), 1, '[#1]:'], [(16, 29, 32, 40)]]
the value is: 该值为:
item_position 1
so I know it can work. 所以我知道它可以工作。 Just wondering if someone can show me the correct code. 只是想知道是否有人可以向我显示正确的代码。 Thanks in advance. 提前致谢。
One way would be to iterate over your list, remembering each item that matches: 一种方法是遍历您的列表,记住与之匹配的每个项目:
In [3]: item_position = [i for i, x in enumerate(list2) if x[0] == (16,29,32,40) ]
In [4]: print("item_position", item_position)
item_position [1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.