looping through two list simultenously

wittempj@hotmail.com martin.witte at gmail.com
Sun Oct 29 17:41:55 EST 2006


CSUIDL PROGRAMMEr wrote:
> folks
> I have two lists
>
>  i am trying to loop thorough them simultenously.
>
> Here is the code i am using
>
> f1 = os.popen('ls  chatlog*.out')
You can replace this by
py> import glob
py> f1 = glob.glob('chatlog*.out')
it will return a list of filenames in f1, so you can skip next two
lines in your code
> data1=f1.readlines()
> f1.close()
>
If you use the glob this step can be skipped too, as glob returns the
filenames, without any whitespace added
> data1=[x.strip() for x in data1]

> f1 = os.popen('ls  chatlog*.txt')
> data=f1.readlines()
> f1.close()
> for eachline in data1 and line in data:
>
>     filename='/root/Desktop/project/'+ eachline
>     print filename
>     outfile=open(filename,'r')
>     filename1='/root/Desktop/project/' + line
>     print filename1
>
now you do the zip as suggested by the other people, but be aware that
it only returns the tuples as long as the shortest list is, so it might
be a good idea to add a test on equality of the number of .log and .txt
files
py> import glob
py> f1 = glob.glob('chatlog*.out')
py> f2 = glob.glob('chatlog*.txt')
py> if len(f1) != len(f2):
py>     print "number of .out files doesn't match number of .txt files"
py> f3 = zip(f1, f2)
now f3 will be somethine like [('chatlog1.out',
'chatlog1.txt'),('chatlog2.out', 'chatlog2.txt')], then you can
continue with your iteration loops


> I get the error that line is not defined.
> Traceback (most recent call last):
>   File "list.py", line 16, in ?
>     for eachline in data1 and line in data:
> NameError: name 'line' is not defined
> 
> Is there any efficient doing this




More information about the Python-list mailing list