reorder a python list to match the order of another python list

Viewed 22

I have two lists:

listA = ['market', 'fraud', 'crime', 'security', 'public', 
'state']

listB = ['security','fraud', 'state']

the elements present in listB needs to be in the same position of the elements of listA. If listA contains any element that listB does not contain, then I need to fill this empty position with the number 0. So far, I only added the zeros to listB (see below). How can I achieve this goal?

difference = len(listA) - len(listB)
c= 0 
while c < b:
  c+=1
  listB.append(0)

my final output should look like:

listC = [0, 'fraud', 0, 'security', 0, 'state']

listC should contain 0 replacing the element that is not in listB. Strings that are present in listB should be in the listC in the same order (index position) they are in listA.

2 Answers

Just create the new list from listA, but substitute 0 if items are not found in listB:

listA = ['market', 'fraud', 'crime', 'security', 'public', 'state']

listB = ['security','fraud', 'state']

listC = [item if item in listB else 0 for item in listA]
print(listC)

Output as requested

Update:

As Mark Ransom points out, if listB is very large, it would be more efficient to search through a set of those elements:

listA = ['market', 'fraud', 'crime', 'security', 'public', 'state']

listB = ['security','fraud', 'state']
slistB = set(listB)

listC = [item if item in slistB else 0 for item in listA]
print(listC)

Same output

the other solution is correct here's another simpler format:

listA = ['market', 'fraud', 'crime', 'security', 'public', 
'state']

listB = ['security','fraud', 'state']
listC=[]
for i in listA:
    if i in listB:
        listC.append(i)
    else:
        listC.append('0')
        
print(listC)
Related