Re: iterating over two sequences at once
From: Peter Otten (__peter___at_web.de)
Date: 07/25/04
- Next message: Christian Tismer: "Re: iterating over two sequences at once"
- Previous message: Bill Dandreta: "Re: iterating over two sequences at once"
- In reply to: Dan: "iterating over two sequences at once"
- Next in thread: Christian Tismer: "Re: iterating over two sequences at once"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 25 Jul 2004 19:44:24 +0200
Dan wrote:
> This is relatively simple, borrowing from my C++/PHP background:
>
> str = "abcdefg"
> str2 = "abcde"
>
> i = 0
> for c in str:
> print c, " ", str2[i]
> i += 2
>
> But that is a C++/PHP way of doing things.
>
>>>From what I've seen of python, I almost expected python to allow:
>
> for c, c2 in str, str2:
>
> But it didn't. I would be very surprised if there isn't another clever
> way of doing the same though.
>>> for c, d in zip("abc", "xyzwillbeignored"):
... print c, d
...
a x
b y
c z
or, if i += 2 isn't there by mistake:
>>> for c, d in zip("abc", "xyzwillbeignored"[::2]):
... print c, d
...
a x
b z
c i
>>>
Using itertools.izip() instead of zip() doesn't create an intermediate list
of tuples which is an advantage when the zip/izip arguments are large
sequences.
> My question to you is, how would you do this? And do you think I should
> propose a PEP for supporting the above for loop syntax? It seems like a
> relatively harmless feature in that it won't break existing code, but
> then I am very new to python.
What you propose already has a meaning and therefore _will_ break existing
code.
>>> for c, d in "ab", "cd":
... print c, d
...
a b
c d
Peter
- Next message: Christian Tismer: "Re: iterating over two sequences at once"
- Previous message: Bill Dandreta: "Re: iterating over two sequences at once"
- In reply to: Dan: "iterating over two sequences at once"
- Next in thread: Christian Tismer: "Re: iterating over two sequences at once"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|