Reputation: 35
I have a list that contains some numbers. I have to search those numbers one by one to check if they are present in 2nd list. But I have to check number from 1st list completely i.e if full match is not there, then remove the last digit from the number and search again till match is found. I have to keep doing this for all digits of each number of list 1.
example:
z = ['48761', '3876', '481']
p = ['3876112','8935']
I pick 3876112
... seach for it in list z
. if no match, I search 387611
, if no match... I seach for 38761
and so on... Any time in the process if a match is found, I have to return match found and then start doing same for 8935
.
Note: If there is no match at all, I need to return "No match" and that is only Once for that number.
z = ['48761', '3876', '481']
p = ['3876112','8935']
for m in range(0,len(p)):
x = p[m]
for i in range(0,len(x)):
y = x
for words in z:
if y == words:
print("Found")
x = x[:-1]
print("Not found")
Result:
Found
Not found
Not found
Also, When I added in between print lines, I noticed with above code, it is running loop one extra time before printing Found.
Upvotes: 0
Views: 263
Reputation: 19414
Since you're working with strings and not actual numbers, you could use str.startswith()
:
z = ['48761', '3876', '481']
p = ['3876112','8935']
res = []
for target in p:
for num in z:
if target.startswith(num):
res.append("Found")
break
else:
res.append("Not found")
Or simply:
res= ["Found" if any(target.startswith(num) for num in z) else "Not Found" for target in p]
And now, assuming your dataframe is df
you can simply do:
df["res"] = res
Upvotes: 3
Reputation: 241
You can try something like this:
p = ['3876112','8935']
z = ['48761', '3876', '481']
z = set(z) # Cast to set for efficient membership search
for elem in p:
found = False
for i in reversed(range(1, len(elem))):
if elem[:i] in z:
found = True
print('Found')
break
if not found:
print('Not found')
The output is:
Found
Not found
thus one output line for each input element of the list p
.
Upvotes: 1
Reputation: 195418
Using str.startswith()
and any()
to short-circuit early:
z = ['48761', '3876', '481']
p = ['3876112','8935']
for num in p:
if any(num.startswith(n) for n in z):
print('Found')
else:
print('Not Found')
Prints:
Found
Not Found
Upvotes: 1
Reputation: 1779
Use slice of string.
z = ['48761', '3876', '481']
p = ['3876112','8935']
for p_ in p:
length = len(p_)
found = False
save = None
for i in range(length):
if p_[:length-i] in z:
found = True
save = p_[:length-i]
if found: print('found', save)
else: print('not found')
The result is:
found 3876
not found
Upvotes: 1