Efficient way of Element lookup in a Python List?

Question!

I have a list of files in a directory. I have to process only certain files from that directory. filelist is my desired file-list. How do I go about achieving this? Not interested in a bash solution since I have to do it all in this one Python script. Thanks much!

for record in result:
    filelist.append(record[0])

print filelist


for file in os.listdir(sys.argv[1].strip() + "/"):
    for file in filelist: #This doesn't work, how else do I do this? If file equals to my desired file-list, then do something.
        print file

Sorry guys, not sure how I missed this! Early morning coding I guess!! Mods, please close it unless someone wants to chip in with an efficient way of doing it.

for file in os.listdir(sys.argv[1].strip() + "/"):
    if file in filelist:
        print file
By : ThinkCode


Answers

It looks like you just want to do something like this:

for file in os.listdir(sys.argv[1].strip()   "/"): 
    if file in filelist:
        print file 

Note that I just changed the second for to an if. However, since you were asking about efficiency, you probably want to change filelist from being a list to being a set or a dict to make the in operator more efficient.

By : Gabe


Something like this:

print [x for x in os.listdir(sys.argv[1].strip()   "/") if x in filelist]
By : demas


Sounds like you want to do a test:

for file in os.listdir(sys.argv[1].strip()   "/"):
    if file in filelist:
        # Found a file in the wanted-list.
        print file
By : unwind


This video can help you solving your question :)
By: admin