繁体   English   中英

根据单独行中另一个列表的值打印一个列表中元素的索引

[英]Print the indices of elements in one list according to the values of another list in seperate lines

A = [['a'], ['a'], ['b'], ['a'], ['b']]
B =  [['a'], ['b']]

我有两个列表A和B。我必须打印列表A的那些元素索引号(索引号+1),这些元素也存在于列表B中。对于列表B的每个元素,我想打印值的索引在列表 A 中按顺序排列在一行中。 我怎样才能解决这个问题?

我的代码:

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

我的代码 Output:

1 1 3 1 3 

预期 output:

1 2 4
3 5

代码将像这样 go 得到 1,2,4 作为 output

for i,x in enumerate(A):
    if x==B[0]:
        print(i+1,end=" ")

一种解决方案是使用字典:

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])))

Output:

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)))

Output:

1 2 4 
3 5 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM