Search code examples
pythonpython-3.xlistindices

Print the indices of elements in one list according to the values of another list in seperate lines and print -1 for missing elements in python


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

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

I have two list, A and B.I have to print those elements index number(index number + 1) separated by space of list A,which elements also exist in list B.For every element of list B,i want to print the indices of the values in list A sequentially in one line.If there is any element of list B,that missing in list A, then i want to print -1 for this element.How can i fix this?

my code:

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:
    if dict_B[key] == []:
        c = 0
        for i,x in enumerate(B):
            if x == list(key):
                c += 1
        for x in range(c):
            if x == c-1:
                print(-1,end=" ")
            else:
                print(-1)
    else:
        for elem in dict_B[key]:
            print(elem,end=' ')
    print()

Output of my code:

-1
-1
-1 
1 2 6 
3 5 

Expected Output:

-1
-1
1 2 6
3 5
-1

Solution

  • You can use collections.defaultdict here.

    from collections import defaultdict
    idx_dict=defaultdict(list)
    
    for idx,[val] in enumerate(A,1):
        idx_dict[val].append(idx)
    
    for [key] in B:
        if key in idx_dict:
            print(' '.join(map(str,idx_dict[key])))
        else:
            print(-1)
    

    Output:

    -1
    -1
    1 2 6
    3 5
    -1