简体   繁体   English

如何在python的嵌套列表中找到列表的索引

[英]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.

相关问题 如果string在list [0]中,python list.index('')无法在list中找到字符串-为什么? 我如何找到它? - python list.index('') fails to find string in list if string is in list[0] - why? how do i find it? 如何在 python 中找到列表的排序位置/索引? - How do I find the sorted position/index of a list in python? 如何使用 python 在嵌套列表中查找和替换字符? - How do i find and replace characters in nested list using python? 在 Python 的嵌套列表中搜索 || 如何匹配 1 索引嵌套列表和 2 索引嵌套列表 - Searching within Nested lists in Python || How do I match a 1-index nested list, with a 2-index nested list 如何在 Python 的嵌套列表中查找给定值的索引? - How to find index of a given value in a nested list in Python? 如何在 Python 中创建嵌套列表 - How do i create a nested list in Python Python:如何在重复的列表中始终找到下一个索引? - Python: How do I consistently find the next index after another index in a list with duplicates? 在 Python 中,如何用另一个列表索引一个列表? - In Python, how do I index a list with another list? Python-如何将嵌套列表拆分为更多列表? - Python - How do I split a nested list into further list? 如何在嵌套列表中找到元素的索引? - How to find the index of an element within nested list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM