我在 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 项。但是,我还想返回最初两个列表中这些元素的索引。我怎么能这样做?
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)