简体   繁体   English

如何在列表列表中获取外部列表元素的索引?

[英]How can I get an index of an outer list element in a list of lists?

I have a list: 我有一个清单:

mylist = [[0, [0]], [2, [1]], [3, [4]], [4, [1, 4]]]

I want to get the index of the element of the outer list given the element. 我想获得给定元素的外部列表元素的索引。

I have tried this, but this only fetches me the outer elements of the list. 我试过这个,但这只是取了我列表的外部元素。

get_index = [outer for outer, inner in mylist]

I want something like this: 我想要这样的东西:

Input: 2
Output: 1

Input: 4
Output: 3

You could use a dictionary comprehension with enumerate to easily look up the index from the first values: 您可以使用带enumerate的字典理解来轻松地从第一个值中查找索引:

d = {i[0]:ix for ix, i in enumerate(mylist)}
# {0: 0, 2: 1, 3: 2, 4: 3}

d[2]
# 1

d[4]
# 3

A function matching the desired input/output behavior: 与所需输入/输出行为匹配的函数:

def loc( x, ml ):
    return [a for a,b in ml].index(x)

You can also create a function to which you pass an Input and get the corresponding index as output 您还可以创建一个传递Input的函数,并将相应的索引作为输出

def get_index(inp):
    idx = [i for i, j in enumerate(mylist) if inp==j[0]]
    return idx[0]

inp = 2
get_index(inp)
# 1

inp = 4
get_index(inp)
# 3

暂无
暂无

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

相关问题 如何获取列表列表中元素的索引 - How to get index of element in list of lists 如何从多维列表中的元素获取索引? - How can I get index from an element in a mulitidimensional list? 如何从两个单独的列表中获取公共 integer 元素的索引并将其插入另一个列表? - How do I get the index of the common integer element from two separate lists and plug it to another list? 如何有效地将系列索引添加到Pandas系列列表数组的每个列表元素中? - How can I add the series index to each list element a Pandas series of arrays of lists efficiently? 如何在列表的组合列表中删除列表的特定元素? - How can I delete a specific element of a list in a combined list of lists? Python如何通过知道列表中列表的第一个元素来获取列表中列表的索引? - Python how do you get the index of a list in a list, by knowing the first element of the list in lists? 如何获取列表列表中的每个元素? - How to get every element in a list of list of lists? 如何每次都将列表的不同元素设置为增量,以便我可以编辑另一个列表元素? - How to get different element of a list evertime to set as an increment so I can edit another lists elements? 如何将列表列表转换为数据帧并将列表的第一个元素作为索引 - How to covert a list of lists into dataframe and make the first element of the lists as the index 在Python中,如何从列表列表中删除某个元素? - In Python, how can I remove a certain element from a list of lists?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM