[issue22353] re.findall() documentation lacks information about finding THE LAST iteration of repeated capturing group (greedy)
Mateusz Dobrowolny added the comment: The official help https://docs.python.org/3/library/re.html?highlight=findall#re.findall in fact contains more information, especially the one mentioned in http://bugs.python.org/issue3384. Regarding my issue - I am afraid it was my misunderstanding, because it looks like Regular Expressions return always LAST match and Python re.findall reutrns what it is said to be: the list of groups. And since I repeat a captured group, I get only the last match. More here for example here: http://www.regular-expressions.info/captureall.html I was learning regexp yesterday, and first I reported this without knowing everytnig about capturing groups. If returning the last match for repeting a capturing group is defined within RegEx itself, than there is no need to mention it in Python documentation... -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue22353 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue22353] re.findall() documentation lacks information about finding THE LAST iteration of repeated capturing group (greedy)
Guido van Rossum added the comment: Then let's close this issue. -- resolution: - not a bug status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue22353 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue22353] re.findall() documentation lacks information about finding THE LAST iteration of reoeated capturing group (greedy)
New submission from Mateusz Dobrowolny: Python 3.4.1, Windows. help(re.findall) shows me: findall(pattern, string, flags=0) Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. It seems like there is missing information regarding greedy groups, i.e. (regular_expression)* Please take a look at my example: -EXAMPLE- import re text = 'To configure your editing environment, use the Editor settings page and its child pages. There is also a ' \ 'Quick Switch Scheme command that lets you change color schemes, themes, keymaps, etc. with a couple of ' \ 'keystrokes.' print('Text to be searched: \n' + text) print('\nSarching method: re.findall()') regexp_result = re.findall(r'\w+(\s+\w+)', text) print('\nRegexp rule: r\'\w+(\s+\w+)\' \nFound: ' + str(regexp_result)) print('This works as expected: findall() returns a list of groups (\s+\w+), and the groups are from non-overlapping matches.') regexp_result = re.findall(r'\w+(\s+\w+)*', text) print('\nHow about making the group greedy? Here we go: \nRegexp rule: r\'\w+(\s+\w+)*\' \nFound: ' + str(regexp_result)) print('This is a little bit unexpected for me: findall() returns THE LAST MATCHING group only, parsing from-left-to-righ.') regexp_result_list = re.findall(r'(\w+(\s+\w+)*)', text) first_group = list(i for i, j in regexp_result_list) print('\nThe solution is to put an extra group aroung the whole RE: \nRegexp rule: r\'(\w+(\s+\w+)*)\' \nFound: ' + str(first_group)) print('So finally I can get all strings I am looking for, just like expected from the FINDALL method, by accessing first elements in tuples.') --END OF EXAMPLE- I found the solution when practicing on this page: http://regex101.com/#python Entering: REGULAR EXPRESSION: \w+(\s+\w+)* TEST STRING: To configure your editing environment, use the Editor settings page and its child pages. There is also a Quick Switch Scheme command that lets you change color schemes, themes, keymaps, etc. with a couple of keystrokes. it showed me on the right side with nice color-coding: 1st Capturing group (\s+\w+)* Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy] Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data I think some information regarding repeated groups should be included as well in Python documentation. BTW: I have one extra question. Searching for 'findall' in this tracker I found this issue: http://bugs.python.org/issue3384 It looks like information about ordering information is no longer in 3.4.1 documentation. Shouldn't this be there? Kind Regards -- assignee: docs@python components: Documentation messages: 226534 nosy: Mateusz.Dobrowolny, docs@python priority: normal severity: normal status: open title: re.findall() documentation lacks information about finding THE LAST iteration of reoeated capturing group (greedy) versions: Python 3.4 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue22353 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue22353] re.findall() documentation lacks information about finding THE LAST iteration of repeated capturing group (greedy)
Changes by Mateusz Dobrowolny mateusz.dobrowo...@gmail.com: -- title: re.findall() documentation lacks information about finding THE LAST iteration of reoeated capturing group (greedy) - re.findall() documentation lacks information about finding THE LAST iteration of repeated capturing group (greedy) ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue22353 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue22353] re.findall() documentation lacks information about finding THE LAST iteration of repeated capturing group (greedy)
Guido van Rossum added the comment: Do you have a specific sentence or paragraph in mind that could be added? Be aware help() just shows what's in the docstring, which is typically abbreviated. The full docs are on docs.python.org. Can you find what you need there? -- nosy: +gvanrossum ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue22353 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue16571] Iterating over inconsistently-indented code block causes execution of code only on last iteration of loop
New submission from Brian Berard: When a loop (for loop in this case) contains multiple lines of code, if the lines are inconsistently indented, the for loop will only execute those lines on the final pass through the loop with no type of warning regarding indentation error. Ex. for i in range(0,10): print I will print on every iteration: %d % i # TAB indented print I will only print on the final iteration: %d % i # 4 spaces -- components: Interpreter Core files: python_test.py messages: 176551 nosy: dimitriprosser priority: normal severity: normal status: open title: Iterating over inconsistently-indented code block causes execution of code only on last iteration of loop type: behavior versions: Python 2.7 Added file: http://bugs.python.org/file28149/python_test.py ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue16571 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue16571] Iterating over inconsistently-indented code block causes execution of code only on last iteration of loop
Changes by Brian Berard dimitripros...@gmail.com: -- type: behavior - enhancement ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue16571 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue16571] Iterating over inconsistently-indented code block causes execution of code only on last iteration of loop
Mark Dickinson added the comment: This is expected behaviour for Python 2.x: Python interprets every TAB character as advancing to the next multiple-of-8 column, regardless of how your editor sees it. It would be too disruptive to change this behaviour in Python 2.x. It's already fixed in Python 3: there it's a syntax error to mix tabs and spaces in this way. Python 2.7 gives a warning if you run with the '-3' flag. -- nosy: +mark.dickinson resolution: - wont fix status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue16571 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue16571] Iterating over inconsistently-indented code block causes execution of code only on last iteration of loop
Changes by Serhiy Storchaka storch...@gmail.com: -- stage: - committed/rejected ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue16571 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue16571] Iterating over inconsistently-indented code block causes execution of code only on last iteration of loop
Ned Batchelder added the comment: @Brian: Your code doesn't run in Python 2.7 as you've shown it, it produces an IndentationError. If your code is actually different, and does run, try running it with the -tt flag on Python, which will warn about inconsistent indentation. -- nosy: +nedbat ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue16571 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue16571] Iterating over inconsistently-indented code block causes execution of code only on last iteration of loop
Brian Berard added the comment: @nedbat I'm able to run that code as is and receive no such error. With the -tt option, I do receive an indentation error. I will keep that in mind. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue16571 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Last iteration?
En Fri, 19 Oct 2007 19:12:49 -0300, Michael J. Fromberger [EMAIL PROTECTED] escribió: Before I affront you with implementation details, here's an example: | from __future__ import with_statement | with last_of(enumerate(file('/etc/passwd', 'rU'))) as fp: | for pos, line in fp: | if fp.marked(): | print Last line, #%d = %s % (pos + 1, line.strip()) In short, last_of comprises a trivial context manager that knows how to iterate over its input, and can also indicate that certain elements are marked. In this case, only the last element is marked. The name is very unfortunate. I'd expect that last_of(something) would return its last element, not an iterator. Even with a different name, I don't like that marked() (a method of the iterator) should be related to the current element being iterated. We could also make the truth value of the context manager indicate the marking, as illustrated here: | with last_of(alphabet soup) as final: | for c in final: | if final: | print Last character: %s % c This is bit artificial, perhaps, but effective enough. Of course, there Again, why should the trueness of final be related to the current element being iterated? is really no reason you have to use with, since we don't really care what happens when the object goes out of scope: You could just as easily write: | end = last_of(xrange(25)) | for x in end: | if end: | print Last element: %s % x Again, why the truth value of end is related to the current x element? But you could also handle nested context, using with. Happily, the machinery to do all this is both simple and easily generalized to other sorts of marking tasks. For example, we could just as well do something special with all the elements that are accepted by a predicate function, e.g., | def isinteger(obj): | return isinstance(obj, (int, long)) | with matching([a, 1, b, 2, c], isinteger) as m: | for elt in m: | if m.marked(): | print '#%s' % elt, | else: | print '(%s)' % elt, | | print I think you are abusing context managers *a*lot*! Even accepting such evil thing as matching(...), the above code could be equally written as: m = matching(...) for elt in m: ... Anyway, a simple generator that yields (elt, function(elt)) would be enough... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
In article [EMAIL PROTECTED], Raymond Hettinger [EMAIL PROTECTED] wrote: [Diez B. Roggisch] out:) But I wanted a general purpose based solution to be available that doesn't count on len() working on an arbitrary iterable. [Peter Otten] You show signs of a severe case of morbus itertools. I, too, am affected and have not yet fully recovered... Maybe you guys were secretly yearning for a magical last element detector used like this: [...] Although there have already been some nice solutions to this problem, but I'd like to propose another, which mildly abuses some of the newer features of Python It is perhaps not as concise as the previous solutions, nor do I claim it's better; but I thought I'd share it as an alternative approach. Before I affront you with implementation details, here's an example: | from __future__ import with_statement | with last_of(enumerate(file('/etc/passwd', 'rU'))) as fp: | for pos, line in fp: | if fp.marked(): | print Last line, #%d = %s % (pos + 1, line.strip()) In short, last_of comprises a trivial context manager that knows how to iterate over its input, and can also indicate that certain elements are marked. In this case, only the last element is marked. We could also make the truth value of the context manager indicate the marking, as illustrated here: | with last_of(alphabet soup) as final: | for c in final: | if final: | print Last character: %s % c This is bit artificial, perhaps, but effective enough. Of course, there is really no reason you have to use with, since we don't really care what happens when the object goes out of scope: You could just as easily write: | end = last_of(xrange(25)) | for x in end: | if end: | print Last element: %s % x But you could also handle nested context, using with. Happily, the machinery to do all this is both simple and easily generalized to other sorts of marking tasks. For example, we could just as well do something special with all the elements that are accepted by a predicate function, e.g., | def isinteger(obj): | return isinstance(obj, (int, long)) | with matching([a, 1, b, 2, c], isinteger) as m: | for elt in m: | if m.marked(): | print '#%s' % elt, | else: | print '(%s)' % elt, | | print Now that you've seen the examples, here is an implementation. The marker class is an abstract base that does most of the work, with the last_of and matching examples implemented as subclasses: | class marker (object): | Generate a trivial context manager that flags certain elements | in a sequence or iterable. | | Usage sample: | with marker(ITERABLE) as foo: | for elt in foo: | if foo.marked(): | print 'this is a marked element' | else: | print 'this is an unmarked element' | | Subclass overrides: | .next() -- return the next unconsumed element from the input. | .marked() -- return True iff the last element returned is marked. | | By default, no elements are marked. | | def __init__(self, seq): | self._seq = iter(seq) | try: | self._fst = self._seq.next() | except StopIteration: | self.next = self._empty | | def _empty(self): | raise StopIteration | | def _iter(self): | while True: | yield self.next() | | def next(self): | out = self._fst | try: | self._fst = self._seq.next() | except StopIteration: | self.next = self._empty | | return out | | def marked(self): | return False | | def __iter__(self): | return iter(self._iter()) | | def __nonzero__(self): | return self.marked() | | def __enter__(self): | return self | | def __exit__(self, *args): | pass A bit verbose, but uncomplicated apart from the subtlety in handling the end case. Here's last_of, implemented as a subclass: | class last_of (marker): | def __init__(self, seq): | super(last_of, self).__init__(seq) | self._end = False | | def next(self): | out = super(last_of, self).next() | if self.next == self._empty: | self._end = True | | return out | | def marked(self): | return self._end And finally, matching: | class matching (marker): | def __init__(self, seq, func): | super(matching, self).__init__(seq) | self._func = func | self._mark = False | | def next(self): | out = super(matching, self).next() | self._mark = self._func(out) | return out | | def marked(self): | return self._mark Generally speaking, you should only have to override .next() and .marked() to make a useful subclass of marker -- and possibly also __init__ if you need some
Re: Last iteration?
Raymond Hettinger pyt...cn.com wrote: More straight-forward version: def lastdetecter(iterable): t, lookahead = tee(iterable) lookahead.next() return izip(chain(imap(itemgetter(0), izip(repeat(False), lookahead)), repeat(True)), t) If this is what you call straightforward - heaven forfend that I ever clap my orbs on something you call convoluted! :-) Faced with this problem, I would probably have used enumerate with a look ahead and the IndexError would have told me I am at the end... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 17, 11:45 pm, Raymond Hettinger [EMAIL PROTECTED] wrote: [Paul Hankin] def lastdetector(iterable): t, u = tee(iterable) return izip(chain(imap(lambda x: False, islice(u, 1, None)), [True]), t) Sweet! Nice, clean piece of iterator algebra. We need a C-speed verion of the lambda function, something like a K combinator that consumes arguments and emits constants. Perhaps, but I think you'll need a better use-case than this :) Actually, would a c-version be much faster? -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
[Diez B. Roggisch] out:) But I wanted a general purpose based solution to be available that doesn't count on len() working on an arbitrary iterable. [Peter Otten] You show signs of a severe case of morbus itertools. I, too, am affected and have not yet fully recovered... Maybe you guys were secretly yearning for a magical last element detector used like this: for islast, value in lastdetecter([1,2,3]): if islast: print 'Last', value else: print value Perhaps it could be written plainly using generators: def lastdetecter(iterable): it = iter(iterable) value = it.next() for nextvalue in it: yield (False, value) value = nextvalue yield (True, value) Or for those affected by morbus itertools, a more arcane incantation would be preferred: from itertools import tee, chain, izip, imap from operator import itemgetter def lastdetecter(iterable): fast iterator algebra lookahead, t = tee(iterable) lookahead.next() t = iter(t) return chain(izip(repeat(False), imap(itemgetter(1), izip(lookahead, t))), izip(repeat(True),t)) Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
def lastdetecter(iterable): fast iterator algebra lookahead, t = tee(iterable) lookahead.next() t = iter(t) return chain(izip(repeat(False), imap(itemgetter(1), izip(lookahead, t))), izip(repeat(True),t)) More straight-forward version: def lastdetecter(iterable): t, lookahead = tee(iterable) lookahead.next() return izip(chain(imap(itemgetter(0), izip(repeat(False), lookahead)), repeat(True)), t) Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
Raymond Hettinger wrote: [Diez B. Roggisch] out:) But I wanted a general purpose based solution to be available that doesn't count on len() working on an arbitrary iterable. [Peter Otten] You show signs of a severe case of morbus itertools. I, too, am affected and have not yet fully recovered... Maybe you guys were secretly yearning for a magical last element detector used like this: Not secretly... def lastdetecter(iterable): it = iter(iterable) value = it.next() for nextvalue in it: yield (False, value) value = nextvalue yield (True, value) as that's what I posted above... def lastdetecter(iterable): fast iterator algebra lookahead, t = tee(iterable) # make it cope with zero-length iterables lookahead = islice(lookahead, 1, None) return chain(izip(repeat(False), imap(itemgetter(1), izip(lookahead, t))), izip(repeat(True),t)) and that's the somebody call the doctor -- now! version ;) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 17, 8:16 am, Raymond Hettinger [EMAIL PROTECTED] wrote: def lastdetecter(iterable): fast iterator algebra lookahead, t = tee(iterable) lookahead.next() t = iter(t) return chain(izip(repeat(False), imap(itemgetter(1), izip(lookahead, t))), izip(repeat(True),t)) More straight-forward version: def lastdetecter(iterable): t, lookahead = tee(iterable) lookahead.next() return izip(chain(imap(itemgetter(0), izip(repeat(False), lookahead)), repeat(True)), t) def lastdetector(iterable): t, u = tee(iterable) return izip(chain(imap(lambda x: False, islice(u, 1, None)), [True]), t) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
[Paul Hankin] def lastdetector(iterable): t, u = tee(iterable) return izip(chain(imap(lambda x: False, islice(u, 1, None)), [True]), t) Sweet! Nice, clean piece of iterator algebra. We need a C-speed verion of the lambda function, something like a K combinator that consumes arguments and emits constants. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
Raymond Hettinger [EMAIL PROTECTED] writes: We need a C-speed verion of the lambda function, something like a K combinator that consumes arguments and emits constants. Some discussion of this is at http://bugs.python.org/issue1673203. I had suggested implementing K through an optional second arg for a proposed identity function but everyone hated that. I'm amused. I had suggested it because I thought that it would be easier than getting two separate functions accepted. -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
Paul Hankin a écrit : On Oct 12, 11:58 am, Florian Lindner [EMAIL PROTECTED] wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i Yes, either use enumerate or just stop the loop early and deal with the last element outside the loop. xs = [1, 2, 3] for x in xs[:-1]: print x print xs[-1] * xs[-1] At least something sensible !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
Diez B. Roggisch wrote: out:) But I wanted a general purpose based solution to be available that doesn't count on len() working on an arbitrary iterable. You show signs of a severe case of morbus itertools. I, too, am affected and have not yet fully recovered... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 12, 5:58 am, Florian Lindner [EMAIL PROTECTED] wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Can this be acomplished somehow? Thanks, Florian Maybe it's a leftover from my C++ days, but I find the iteration-based solutions the most appealing. This is a refinement of the previous post by Diez Roggisch. The test method seems to match your desired idiom pretty closely: def signal_last(lst): last2 = None it = iter(lst) try: last = it.next() except StopIteration: last = None for last2 in it: yield False, last last = last2 yield True, last def test(t): for isLast, item in signal_last(t): if isLast: print ...and the last item is, item else: print item test(ABC) test([]) test([1,2,3]) Prints: A B ...and the last item is C ...and the last item is None 1 2 ...and the last item is 3 -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 14, 8:00 am, Paul McGuire [EMAIL PROTECTED] wrote: On Oct 12, 5:58 am, Florian Lindner [EMAIL PROTECTED] wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Can this be acomplished somehow? Thanks, Florian Maybe it's a leftover from my C++ days, but I find the iteration-based solutions the most appealing. This is a refinement of the previous post by Diez Roggisch. The test method seems to match your desired idiom pretty closely: def signal_last(lst): last2 = None it = iter(lst) try: last = it.next() except StopIteration: last = None for last2 in it: yield False, last last = last2 yield True, last This yields a value when the iterator is empty, which Diez's solution didn't. Logically, there is no 'last' element in an empty sequence, and it's obscure to add one. Peter Otten's improvement to Diez's code looks the best to me: simple, readable and correct. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
Peter Otten schrieb: Diez B. Roggisch wrote: Florian Lindner wrote: can I determine somehow if the iteration on a list of values is the last iteration? def last_iter(iterable): it = iter(iterable) buffer = [it.next()] for i in it: buffer.append(i) old, buffer = buffer[0], buffer[1:] yield False, old yield True, buffer[0] This can be simplified a bit since you never have to remember more than on item: def mark_last(items): ... items = iter(items) ... last = items.next() ... for item in items: ... yield False, last ... last = item ... yield True, last ... list(mark_last([])) [] list(mark_last([1])) [(True, 1)] list(mark_last([1,2])) [(False, 1), (True, 2)] Nice. I tried to come up with that solution in the first place - but most probably due to an java-coding induced brain overload it didn't work out:) But I wanted a general purpose based solution to be available that doesn't count on len() working on an arbitrary iterable. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 14, 5:58 am, Paul Hankin [EMAIL PROTECTED] wrote: On Oct 14, 8:00 am, Paul McGuire [EMAIL PROTECTED] wrote: def signal_last(lst): last2 = None it = iter(lst) try: last = it.next() except StopIteration: last = None for last2 in it: yield False, last last = last2 yield True, last This yields a value when the iterator is empty, which Diez's solution didn't. Logically, there is no 'last' element in an empty sequence, and it's obscure to add one. Peter Otten's improvement to Diez's code looks the best to me: simple, readable and correct. Of course! For some reason I thought I was improving Peter Otten's version, but when I modified my submission to behave as you stated, I ended right back with what Peter had submitted. Agreed - nice and neat! -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 12, 12:58 pm, Florian Lindner [EMAIL PROTECTED] wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Can this be acomplished somehow? Thanks, Florian If you want to do this over a list or a string, I'd just do: for element in iterable[:-1]: print iterable print iterable[-1] * iterable[-1] No need for it to get more advanced than that :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
Diez B. Roggisch wrote: Florian Lindner wrote: can I determine somehow if the iteration on a list of values is the last iteration? def last_iter(iterable): it = iter(iterable) buffer = [it.next()] for i in it: buffer.append(i) old, buffer = buffer[0], buffer[1:] yield False, old yield True, buffer[0] This can be simplified a bit since you never have to remember more than on item: def mark_last(items): ... items = iter(items) ... last = items.next() ... for item in items: ... yield False, last ... last = item ... yield True, last ... list(mark_last([])) [] list(mark_last([1])) [(True, 1)] list(mark_last([1,2])) [(False, 1), (True, 2)] Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 12, 11:58 am, Florian Lindner [EMAIL PROTECTED] wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Can this be acomplished somehow? Another suggestion: l = [1, 2, 3] for i in l[:-1]: print i i = l[-1] print i*i James -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 12, 11:58 am, Florian Lindner [EMAIL PROTECTED] wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i Yes, either use enumerate or just stop the loop early and deal with the last element outside the loop. xs = [1, 2, 3] for x in xs[:-1]: print x print xs[-1] * xs[-1] -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
Florian Lindner wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Can this be acomplished somehow? def last_iter(iterable): it = iter(iterable) buffer = [it.next()] for i in it: buffer.append(i) old, buffer = buffer[0], buffer[1:] yield False, old yield True, buffer[0] for last, i in last_iter(xrange(4)): if last: print i*i else: print i Diez -- http://mail.python.org/mailman/listinfo/python-list
Last iteration?
Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Can this be acomplished somehow? Thanks, Florian -- http://mail.python.org/mailman/listinfo/python-list
RE: Last iteration?
Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Something like: myList = [1, 2, 3] for i, j in enumerate(myList): if i == len(myList)-1: print j*j else: print j Cheers, Andreas Tawn Lead Technical Artist Ubisoft Reflections -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
Florian Lindner wrote: can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Can this be acomplished somehow? You could do this: l = [1,2,3] s = len(l) - 1 for i, item in enumerate(l): # Py 2.4 if i == s: print item*item else: print item Or, you could look one step ahead: l = [1,2,3] next = l[0] for item in l[1:]: print next next = item print next * next Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Fri, 2007-10-12 at 12:58 +0200, Florian Lindner wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Here's another solution: mylist = [1,2,3] for j,i in reversed(list(enumerate(reversed(mylist: if j==0: print i*i else: print i ;) -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Last iteration?
On Oct 12, 2:18 pm, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 2007-10-12 at 12:58 +0200, Florian Lindner wrote: Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in [1, 2, 3]: if last_iteration: print i*i else: print i that would print 1 2 9 Here's another solution: mylist = [1,2,3] for j,i in reversed(list(enumerate(reversed(mylist: if j==0: print i*i else: print i Nice! A more 'readable' version is: mylist = [1,2,3] for not_last, i in reversed(list(enumerate(reversed(mylist: if not_last: print i else: print i * i -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list