在Python列表中查找元素的有效方法?
我有一个目录中的文件列表。我必须只处理该目录中的某些文件。 filelist 是我想要的文件列表。我该如何实现这一目标?对 bash 解决方案不感兴趣,因为我必须在这个 Python 脚本中完成这一切。非常感谢!
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
抱歉各位,不知道我是怎么错过这个的!我猜是一大早编码!!模组们,请关闭它,除非有人想要以有效的方式进行操作。
for file in os.listdir(sys.argv[1].strip() + "/"):
if file in filelist:
print file
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果顺序和唯一性不重要,您可以使用
set
交集,这会更高效。改进示例:
If order and uniqueness don't matter, you can use a
set
intersection, which will be much more efficient.Example of improvement:
听起来你想做一个测试:
Sounds like you want to do a test:
看起来您只想做这样的事情:
请注意,我刚刚将第二个
for
更改为if
。但是,由于您询问效率,您可能希望将filelist
从list
更改为set
或dict
使in
运算符更加高效。It looks like you just want to do something like this:
Note that I just changed the second
for
to anif
. However, since you were asking about efficiency, you probably want to changefilelist
from being alist
to being aset
or adict
to make thein
operator more efficient.像这样的东西:
Something like this: