Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #30428
| Path | csiph.com!usenet.pasdenom.info!news.albasani.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail |
|---|---|
| From | Neil Cerutti <neilc@norwich.edu> |
| Newsgroups | comp.lang.python |
| Subject | Re: howto handle nested for |
| Date | 28 Sep 2012 20:38:56 GMT |
| Organization | Norwich University |
| Lines | 63 |
| Message-ID | <acmg70F189sU1@mid.individual.net> (permalink) |
| References | <k44cr4$jtj$1@ger.gmane.org> <mailman.1557.1348844688.27098.python-list@python.org> |
| Mime-Version | 1.0 |
| Content-Type | text/plain; charset=us-ascii |
| Content-Transfer-Encoding | 7bit |
| X-Trace | individual.net qzgNrD3eZz1wWFfhvJbm+wArd0btlH1kzE1kpKoyO5nMPkyg3H7UcOCiLZO8VoBF7O |
| Cancel-Lock | sha1:LskeCUf5aHQJwvuBKYC+b60sPp4= |
| User-Agent | slrn/0.9.9p1/mm/ao (Win32) |
| Xref | csiph.com comp.lang.python:30428 |
Show key headers only | View raw
On 2012-09-28, Laszlo Nagy <gandalf@shopzeus.com> wrote: > In your example, it seem that the iterable of the for loop is > always the same: range(n_sysms). It seems to be a number. Is > that true? If that is so, then here is something useful: > > import copy > > class MultiLevelIterator(object): > def __init__(self,levels,n): > assert(levels>0) > assert(n>0) > self.levels = levels > self.values = [0]*levels > self.n = n > > def __iter__(self): > return self > > def next(self): > res = copy.copy(self.values) > idx = self.levels-1 > while idx>=0: > self.values[idx]+=1 > if self.values[idx]>=self.n: > self.values[idx] = 0 > idx-=1 > else: > return res > raise StopIteration > > i = MultiLevelIterator(2,3) > for values in i: > print values > > This will print: > > [0, 0] > [0, 1] > [0, 2] > [1, 0] > [1, 1] > [1, 2] > [2, 0] > [2, 1] It looks like you might have missed the last one. Also, be sure to check itertools for occasionally for cool stuff like this. >>> for values in itertools.product(range(3), repeat=2): ... print(values) ... (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2) -- Neil Cerutti
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Re: howto handle nested for Laszlo Nagy <gandalf@shopzeus.com> - 2012-09-28 17:04 +0200 Re: howto handle nested for Neil Cerutti <neilc@norwich.edu> - 2012-09-28 20:38 +0000
csiph-web