简体   繁体   English

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

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

I have the following lists: 我有以下列表:

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

If I use b.index("f") I get 0. What I want it to output, however, is 5. How can I get the index of "f" in list a through the list b? 如果我使用b.index("f")我将得到0。但是,我希望输出的是5。如何通过列表b获得列表a中的“ f”索引?

You can't, because the elements in a are strings which don't "know" where they are in the list. 您不能这样做,因为a中的元素是不“知道”它们在列表中位置的字符串。 Hence when you index them out of the list (eg a[5] ), the strings can't tell you where they came from in the list. 因此,当您将它们从列表中索引出来(例如a[5] )时,字符串无法告诉您它们在列表中的来源。


I'm not sure what your aim is through creating this new list, but you could just store the indexes of the elements rather than the elements themselves in b . 我不确定创建此新列表的目的是什么,但是您可以仅将元素的索引而不是元素本身存储在b

eg 例如

b = [5, 4, 3]

which would allow you to then create a function which would "get the index of [an element] in list a through list b : 这样您就可以创建一个函数,该函数“将获取列表a到列表b中[[元素]的索引:

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

which works as if there were some magical method to get the index of elements in b as if they were in a : 好像有某种神奇的方法来获取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

note how even though 'a' is in the list a , since it is not in the list b , it is not returned 请注意,即使'a'在列表a ,但由于它不在列表b ,因此也不会返回

This isn't possible. 这是不可能的。 Elements of b are resolved to strings and lose all knowledge of their indices in a . b元素被解析为字符串,并且丢失了它们在a中的索引的所有知识。 You can write a small class to store the value and index: 您可以编写一个小类来存储值索引:

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']

In this way, b would be ["f", "e", "d"] and the indexes of that elements are 0,1,2. 这样,b将为["f", "e", "d"]并且该元素的索引为0,1,2。 You can create b in this way, though: 您可以通过以下方式创建b:

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

Otherwise, if you want indexes and values you can use a dictionary: 否则,如果需要索引和值,则可以使用字典:

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