Python的一些小知识点_5

本文最后更新于2015年1月8日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!

1.如何比较两个文件的创建/修改时间?

确定搜索关键字:python compare file mtime/ctime

http://search.aol.com/aol/search?q=python+compare+file+ctime

2.如何按照某个特定的顺序读取文件内容进行合并?

确定搜索关键字:python read/concatenate multiple files in order


3.如何删除Python的字典中的某个元素?

http://search.aol.com/aol/search?q=python+delete+dict+items

dict_del

总而言之就2种方式:del语句 或 重新赋值覆盖掉

4.如何删除Python的list中的某个元素?

list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

https://docs.python.org/2/tutorial/datastructures.html#more-on-lists #Python的list操作集合

5.如何用Python移动文件?

http://search.aol.com/aol/search?q=python+move+file+to+another+dir

推荐使用:shutil.move()

http://stackoverflow.com/questions/8858008/moving-a-file-in-python

os.rename() or shutil.move()
Although os.rename() and shutil.move() will both rename files, the command that is closest to the Unix mv command is shutil.move(). The difference is that os.rename() doesn’t work if the source and destination are on different disks, while shutil.move() doesn’t care what disk the files are on.

6.Python中的sleep方法该怎么写?

http://search.aol.com/aol/search?q=python+sleep

http://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python

Here is another example where something is run once a minute:

7.Python中的字符串替换(长字符串替换的效率如何还不清楚?)

As long as you can make do with str.replace(), you should use it. It avoids all the pitfalls of regular expressions (like escaping), and is generally faster.
总而言之,建议就是:可以用字符串原生函数的地方就不要用正则表达式去完成类似的工作,效率隔了好多呢!

8.Python中的set和list的对比

http://stackoverflow.com/questions/2831212/python-sets-vs-lists

即,效率和具体的应用有关:set结构在用于判断某个元素是否存在的时候是非常快的;但在迭代枚举包含的元素时,要比list慢。

9.Python的join方法的使用

如何连接对象数组?

http://stackoverflow.com/questions/497765/python-string-joinlist-on-object-array-rather-than-string-array

解法一:列表推导式(或生成器表达式)

解法二:善用map方法

https://docs.python.org/2/library/stdtypes.html#str.join

10.Python的os.walk()方法返回内容的排序

之前一直使用Python的os.walk()方法遍历目录,也没什么其它的要求,用起来也是很爽的,但是近来有个需求:对os.walk()返回的列表按文件名/创建时间进行排序,就没法使用os.walk()自己返回的内容列表了,因为你不清楚它到底是怎么排序的,今天特地去搜了一下,原来如此:

http://search.aol.com/aol/search?q=python+os.walk%28%29+order

http://stackoverflow.com/questions/18282370/python-os-walk-what-order

所以,如果你有自己的需要,可以使用sort或sorted()方法自定义进行次排序。

借用str.index()或str.rindex()方法 && 列表切片可以达到某个目的:

 

声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!
https://ixyzero.com/blog/archives/1772.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注