根据另一个列表的值,分行打印一个列表中元素的索引。

问题描述 投票:-2回答:2
A = [['a'], ['a'], ['b'], ['a'], ['b']]
B =  [['a'], ['b']]

我有两个列表A和B,我必须打印列表A中的元素索引号(索引号+1),这些元素在列表B中也存在。如何解决这个问题?

我的代码

for i,x in enumerate(A):
    for y in B:
        if x == y:
            print(A.index(x)+1,end=" ")

我的代码输出:

1 1 3 1 3 

预期的输出:

1 2 4
3 5
python python-3.x list indexing duplicates
2个回答
1
投票

一个解决方案是使用字典。

A = [['a'], ['a'], ['b'], ['a'], ['b']]
B =  [['a'], ['b']]
dict_B = dict([(b[0],[]) for b in B])
for i,a in enumerate(A):
    if a[0] in dict_B:
        dict_B[a[0]].append(i+1)

for key in dict_B:
    print(' '.join(map(str, dict_B[key])))

输出。

1 2 4 
3 5 

另一种方法是使用numpy。

import numpy as np
np_array = np.array(A)
for elem in B:
    item_index = np.where(np_array==elem)
    print(' '.join(map(str, item_index[0]+1)))

输出:

1 2 4 
3 5 

2
投票

这段代码是这样的,可以得到1,2,4的输出结果

for i,x in enumerate(A):
    if x==B[0]:
        print(i+1,end=" ")
© www.soinside.com 2019 - 2024. All rights reserved.