Loop structure is a common structure for programming. The loop is especially required when processing serialized objects (such as list, dict, and tuple. However, in Python, there is a more convenient way of processing, that is, list derivation and function programming.
If we want to find out a directory such as "C: //", all files with the extension ". txt" are implemented in three ways:
Loop:
Import OS
Dirpath = 'C ://'
Result = []
For filename in OS. listdir (dirpath): # list all directory items in this directory
If OS. Path. isfile (OS. Path. Join (dirpath, filename)/# determine whether the directory item is a file
And OS. Path. splitext (filename) [1] = '.txt ': Your contents are ended with '.txt'
Result. append (filename)
List derivation:
Import OS
Dirpath = 'C ://'
Result = [filename for filename in OS. listdir (dirpath) If OS. Path. isfile (OS. Path. Join (dirpath, filename ))/
And OS. Path. splitext (filename) [1] = '.txt ']
# Using list derivation to generate a list is much more convenient
Function programming method:
Import OS
Dirpath = 'C ://'
Result = filter (lambda FN: (OS. path. isfile (OS. path. join (dirpath, FN) and OS. path. splitext (FN) [1]) and true or false )/
, OS. listdir (dirpath ))
The first step is to define lambda to receive a directory name. If the directory name is '.txt 'with the extension and is a file
# True is returned. Otherwise, false is returned. 'A and B or C' is a three-object operator similar to C language 'a? B: C' habits
# Usage. But it is different. If you want to use this method, you must ensure that the value of B must be true and cannot be
# False, none, [], {}, and so on are all false values. Otherwise, this operation will produce unexpected results.
# Filter (F, list) is to execute the f function operation on each value of the input list, and return all the items in the true list returned by F.
If you look at the code written by the python Masters, it is simply expressions, Lambda functions, filter (), map (), reduce (),'... and... or... ', list Derivation Set. The use of FP programming can lead to faster development of less code and fewer errors.
Data Connection:
Http://www-900.ibm.com/developerWorks/cn/linux/sdk/python/charm-10/index.shtmlCute Python: function programming in Python
Http://www.chinesepython.org/pythonfoundry/limodoupydoc/dive/html/index.html deep into Python (dive into Python)