在两个 python 列表中查找常见项的索引

kon*_*tin 2 python list

我在 python list_A 和 list_B 中有两个列表,我想找到它们共享的公共项目。我这样做的代码如下:

both = []
for i in list_A:
    for j in list_B:
        if i == j:
            both.append(i)
Run Code Online (Sandbox Code Playgroud)

列表中的common 最终包含了common 项。但是,我还想返回最初两个列表中这些元素的索引。我怎么能这样做?

kos*_*nik 5

for如果有更好的方法,建议在 python 中尽可能避免使用循环。使用python可以高效地找到两个列表中的公共元素,set如下所示

both = set(list_A).intersection(list_B)
Run Code Online (Sandbox Code Playgroud)

然后你可以使用内置index方法找到索引

indices_A = [list_A.index(x) for x in both]
indices_B = [list_B.index(x) for x in both]
Run Code Online (Sandbox Code Playgroud)

  • “建议在 python 中尽可能避免使用 for 循环”=> 绝对不是。建议(不仅是在 Python 中)当存在已知的高效解决方案且实施起来并不复杂(或复杂得多)时,应避免编写低效代码。 (2认同)