python - Loop to Match Parts of List -


my code:

#prints out samenodes f = open('newerfile.txt') mylist = list(f) count = 0 = 1 while count < 1000:     if mylist[i] == mylist[i+12] , mylist [i+3] == mylist [i+14]:          print mylist[i]     count = count+1         = i+12 

my intention @ elt 1, elt 2. if elt 1 == elt 13 , elt 2==elt 14 want print elt 1. then, want @ elt 13 , elt 14. if elt 2 matches elt 13+12 , elt 14 matches elt 14+12 want print it. etc...

there parts of list fit criteria, program returns no output.

to iterate on multiple lists (technically, iterables) in "lockstep", can use zip. in case, want iterate on 4 versions of mylist, offset 0, 12, 2 , 13.

zippedlists = zip(mylist, mylist[12:], mylist[2:], mylist[13:]) 

next, want 0th, 12th, 24th, etc elements. done slice:

slicedlist = zippedlists[::12] 

then can iterate on that:

for elt1, elt13, elt2, elt14 in slicedlist:     if elt1 == elt13 , elt2 == elt14:         print elt1 

putting file operations, get

#prints out samenodes f = open('newerfile.txt') mylist = list(f)  zippedlists = zip(mylist, mylist[12:], mylist[2:], mylist[13:]) slicedlist = zippedlists[::12]  elt1, elt13, elt2, elt14 in slicedlist:     if elt1 == elt13 , elt2 == elt14:         print elt1 

code considered more "pythonic" current version, using list indexes discouraged when iterating on list.

note if you've got huge number of elements in list above code creates (and destroys @ point) 5 lists. therefore, may better memory performance if use equivalent functions in itertools, uses lazy iterators prevent copying lists needlessly:

from itertools import islice, izip  #prints out samenodes f = open('newerfile.txt') mylist = list(f)  zippedlists = itertools.izip(mylist, islice(mylist, 12), islice(mylist, 2), islice(mylist, 13)) slicedlist = itertools.islice(zippedlists, 0, none, 12)  elt1, elt13, elt2, elt14 in slicedlist:     if elt1 == elt13 , elt2 == elt14:         print elt1 

there's way in itertools avoid slurping entire file mylist, i'm not sure remember - think use case itertools.tee.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -