all pairs of items in a list without indexing?
Michael Sparks
zathras at thwackety.com
Tue Sep 28 18:01:58 EDT 2004
On Tue, 28 Sep 2004, Steven Bethard wrote:
> So I need to do something like:
>
> for i in range(len(l)):
> for j in range(i+1, len(l)):
> # do something with (l[i], l[j])
>
> where I get all pairs of items in a list (where I'm thinking of pairs
> as sets, not tuples, so order doesn't matter). There isn't really
> anything wrong with the solution here, but since Python's for-each
> construction is so nice, I usually try to avoid range(len(..)) type
> calls and list indexing when I can... Is there any way to do this
> without indexing, e.g.:
You want to do this: (eg based on what it sounds like you want to do)
>>> taglist=["WINDOW", [10,10,40,40], "TITLE", "Hello World"]
>>> for i in pairs(taglist):
... print i
...
('WINDOW', [10, 10, 40, 40])
('TITLE', 'Hello World')
>>>
So let's just write pairs:
def pairs(l):
x=iter(l)
while 1:
yield x.next(),x.next()
There might be a more trivial way of doing this, but this is the first
approach that sprang to mind. This doesn't strictly speaking require a
list as source, and obviously doesn't require an intermediate list.
Regards,
Michael.
More information about the Python-list
mailing list