繁体   English   中英

如何在嵌套列表中找到元素的索引?

[英]How to find the index of an element within nested list?

我有以下列表:

a = ["a", "b", "c", "d", "e", "f"]
b = [a[5], a[4], a[3]]

如果我使用b.index("f")我将得到0。但是,我希望输出的是5。如何通过列表b获得列表a中的“ f”索引?

您不能这样做,因为a中的元素是不“知道”它们在列表中位置的字符串。 因此,当您将它们从列表中索引出来(例如a[5] )时,字符串无法告诉您它们在列表中的来源。


我不确定创建此新列表的目的是什么,但是您可以仅将元素的索引而不是元素本身存储在b

例如

b = [5, 4, 3]

这样您就可以创建一个函数,该函数“将获取列表a到列表b中[[元素]的索引:

def get_ind_in_a_thru_b(e):
    i = a.index(e)
    if i in b: return i
    else: raise ValueError

好像有某种神奇的方法来获取b中元素的索引一样,就像它们在a

>>> get_ind_in_a_thru_b('f')
5
>>> get_ind_in_a_thru_b('g')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in get_ind_in_a_thru_b
ValueError: 'g' is not in list
>>> get_ind_in_a_thru_b('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in get_ind_in_a_thru_b
ValueError

请注意,即使'a'在列表a ,但由于它不在列表b ,因此也不会返回

这是不可能的。 b元素被解析为字符串,并且丢失了它们在a中的索引的所有知识。 您可以编写一个小类来存储值索引:

from operator import attrgetter

a = ["a", "b", "c", "d", "e", "f"]

class GetItemPos():
    def __init__(self, L, idx):
        self.idx = idx
        self.var = L[idx]

b = [GetItemPos(a, 5), GetItemPos(a, 4), GetItemPos(a, 3)]

indices = list(map(attrgetter('idx'), b))  # [5, 4, 3]
values = list(map(attrgetter('var'), b))   # ['f', 'e', 'd']

这样,b将为["f", "e", "d"]并且该元素的索引为0,1,2。 您可以通过以下方式创建b:

b = [a.index(a[5]), a.index(a[4]), a.index(a[3])]

否则,如果需要索引和值,则可以使用字典:

b = {a[3]: a.index(a[3]), a[4]: a.index(a[4]),a[3]: a.index(a[3])}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM