I have 3 lists :
A = [32, 33, 54, 66, 67]
B = [33, 4, 67]
C = ['A', 'B', 'C']
What i'm trying to do is that i want to check if for every element in list A is in B, then it should append an element from C by order to a list D, if not, then it should append an empty string, and here is the result i'm looking for :
D = ['', 'A', '', '', 'B']
and here is what i wrote, but i get back a nested list C of all elements inside it in every position where A is in B, so i should also loop for every element in C, can you please tell me how i can do that ?
D = []
for a in A:
if a in B:
D.append(C)
else:
D.append('')
result: D = ['', [A, B, C], '', '', [A, B, C]]
thank you so much
CodePudding user response:
Maybe you can try this code first:
Explain: you want to advance the item in list C if the required condition met. Using the iter is like a pointer to loop and next will go to next item.
expected = ['', 'A', '', '', 'B']
it = iter(C) # it's looping C as a pointer
D = []
for x in A:
if x in set(B):
D.append(next(it))
else:
D.append('')
print(D)
# ['', 'A', '', '', 'B'] == expected *result*