python - 如何在嵌套列表中查找元素的索引?

标签 python python-3.x

我有以下列表:

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/

相关文章:

python-3.x - Python错误,我做得完全正确,但出现错误

linux - Raspberry pi 2 os.System() 命令返回 0

Python内存消耗导致网络套接字连接崩溃

python - 从格式化字符串打印 unicode

python - 从python函数插入mysql表

python - 使用 rpy2 从 Python 调用自定义函数

python - 如何在 Jupyter Notebook 中从 URL 插入图像(Markdown)

Python3从PID获取进程基地址

Python——Pandas 找不到文件,但 numpy 可以

python - 如何在基于通用类的 View 中更改 django 中的时间格式