[Tutor] replacing lists with iterators (original) (raw)
tpc at csua.berkeley.edu tpc at csua.berkeley.edu
Wed Jul 21 23:09:12 CEST 2004
- Previous message: [Tutor] how popen works?
- Next message: [Tutor] replacing lists with iterators
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
hi everybody, I wrote a program consisting of three scripts to automate encoding of WAVs to MP3s, and while putting in the finishing touches I realized I was using some constructs that many experienced Python programmers would frown upon. For instance, in one function that takes two lists as arguments I used map to iterate through both lists at the same time to set up a source and target for an os.system command. I've been reading how lists, which are completed sequences, can now be replaced with iterators, which are lazy sequences, to make more efficient use of memory. I would like to know how: *) you would use a iterator to store the source and target paths *) to iterate over two iterables at the same time
def getListOfFullPathsToWAVs(SOURCE_DOCUMENT_ROOT): listOfFullPathsToWAVs = [] for rootdir, subdir, files in walk(SOURCE_DOCUMENT_ROOT): for filename in files: if filename.endswith('.wav'): fullPath = join(rootdir, filename) listOfFullPathsToWAVs.append(fullPath) return listOfFullPathsToWAVs
def getListOfFullPathsToTargets(listOfFullPathsToWAVs, TARGET_FILE_TYPE): listOfFullPathsToTargets = [] for fullPathToWAV in listOfFullPathsToWAVs: fullPathToWAV = fullPathToWAV.replace(SOURCE_DOCUMENT_ROOT, TARGET_DOCUMENT_ROOT) filenameTuple = splitext(basename(fullPathToWAV)) fullPath = dirname(fullPathToWAV) + sep + TARGET_FILE_TYPE + sep + filenameTuple[0] + "." + TARGET_FILE_TYPE listOfFullPathsToTargets.append(fullPath) return listOfFullPathsToTargets
def executeSystemCommandToEncodeWAVsAsTargets(listOfFullPathsToWAVs, listOfFullPathsToTargets): for fullPathToWAV, fullPathToTarget in map(None, listOfFullPathsToWAVs, listOfFullPathsToTargets): fullPathTargetTuple = splitext(fullPathToTarget) if fullPathTargetTuple[1] == '.mp3': system("lame % s % s") % (fullPathToWAV, fullPathToTarget)
- Previous message: [Tutor] how popen works?
- Next message: [Tutor] replacing lists with iterators
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]