我有以下列表:
a = ["a", "b", "c", "d", "e", "f"]
b = [a[5], a[4], a[3]]
如果我使用 b.index("f")
我得到 0。然而,我希望它输出的是 5。如何获得列表 a 中“f”的索引通过列表 b?
最佳答案
你不能,因为 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
中,它不返回
关于python - 如何在嵌套列表中查找元素的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52018789/