Reputation: 13
I have an array, p=(1,2,4,5,7,10...) and I would like to input a 0 in where the array deviates from f=(1,2,3,4,5,6...). I have tried using nested for loops but I can't work out how to make the desired output=(1,2,0,4,5,0,7,0,0,10...) using python.
This is all I have really got so far, but it iterates for p[0] with all the elements of f before moving on to p[1] and I don't know how to prevent this:
for x in f:
for y in p:
if x==y:
print(x)
break
else:
print('0')
Thank you!
Upvotes: 0
Views: 133
Reputation: 122
You don't need a nested loop, just iterate through the full numbers' array and insert a zero. Example
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15]
f = [1,2,4,5,6,7,10,14,15]
for index,i in enumerate(p):
if i == f[index]:
pass
else:
f.insert(index, 0)
Result
[1, 2, 0, 4, 5, 6, 7, 0, 0, 10, 0, 0, 0, 14, 15]
Upvotes: 0
Reputation: 2518
code:
p =(1,2,4,5,7,10)
f =tuple(range(1,11))
for x in f:
for y in p:
if x == y:
print(x)
break
else:
print('0')
result:
1
2
0
4
5
0
7
0
0
10
Upvotes: 0
Reputation: 10541
I'd suggest to make p
a set so that checking membership is fast:
>>> p = (1,2,4,5,7,10)
>>> p_set = set(p)
>>> tuple([i if i in p_set else 0 for i in range(11)])
(0, 1, 2, 0, 4, 5, 0, 7, 0, 0, 10)
Upvotes: 1