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