Reputation: 33
I know this might be an already answered question but I searched a lot and I can't seem to find the answer that I'm looking for.
Maybe I am not understanding this.. Here is what I have:
myarray = ['[email protected]', '[email protected]']
img = ['image003.jpg', 'test', 'image004.jpg']
I am trying to make a loop to check if img is in myarray.
I tried with if any(i in img for m in myarrar)
or with a loop that try every element in my array by doing img.find(myarray[i])
Could someone help me with this?
Upvotes: 1
Views: 49
Reputation: 103834
You can use str.partition in a set comprehension to get the file names (assuming that @
delimits the filename from some other data in that list of strings):
>>> myarray = ['[email protected]', '[email protected]']
>>> {e.partition('@')[0] for e in myarray}
{'image003.jpg', 'image004.jpg'}
Then use a set intersection to test membership against the list img
:
>>> img = ['image003.jpg', 'test', 'image004.jpg']
>>> {e.partition('@')[0] for e in myarray} & set(img)
{'image003.jpg', 'image004.jpg'}
If you wanted to have the index of each element in img
that is in myarray
you could do:
ref={e.partition('@')[0] for e in myarray}
for i,fn in enumerate(img):
if fn in ref: print(i,fn)
Or, more tersely:
>>> [(i,fn) for i,fn in enumerate(img) if fn in {e.partition('@')[0] for e in myarray}]
[(0, 'image003.jpg'), (2, 'image004.jpg')]
Upvotes: 1
Reputation: 54203
None of the filenames in img
do exist in myarray
. However, they exist in some of the elements in myarray
, so you need one more layer of loops.
any(fname in s for s in myarray for fname in img)
If you need the index that things are present in:
for i, s in enumerate(myarray):
if any(fname in s for fname in img):
print(i)
Upvotes: 2