[Tutor] Dynamically assign variable names to tuple objects

Emile van Sebille emile at fenx.com
Tue Mar 1 21:14:13 CET 2011

On 3/1/2011 11:49 AM Sean Carolan said...
>> My advice would be to go read up on the zip() function and the
>> str.join() function. Then, if you are using python 2.x, go find
>> itertools.izip. It does the same thing as zip but it's more memory
>> efficient. With those two you can do it in about two lines or so (and
>> maybe a few for set up and clarity and such).
> This is what I've got so far:
> import sys
> myfiles = sys.argv[1:]
> for i in zip(open(myfiles[0]), open(myfiles[1]), open(myfiles[2])):
>      print " ".join(i)
> How would you:
> 1.  zip an arbitrary number of files in this manner?  I hard-coded it
> to do only three.

One way:

for i in zip([ open(filename) for filename in myfiles ])

> 2.  Strip out trailing spaces and line breaks from the lines in each file?

Convert the file contents before zip'ing -- so add

def cleanedup(filename):
     return [ line.strip() for line in open(filename) ]

Then your loop looks like:

for i in zip([ cleanedup(filename) for filename in myfiles ])



More information about the Tutor mailing list