簡體   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