all pairs of items in a list without indexing?
Steven Bethard
steven.bethard at gmail.com
Tue Sep 28 17:57:57 EDT 2004
On Tue, 28 Sep 2004 23:01:58 +0100 (BST), Michael Sparks wrote:
> So let's just write pairs:
>
> def pairs(l):
> x=iter(l)
> while 1:
> yield x.next(),x.next()
This generates all *successive* pairs. I need *all* pairs.
>>> l = range(4)
>>> for i in range(len(l)):
... for j in range(i+1, len(l)):
... print (l[i], l[j])
...
(0, 1)
(0, 2)
(0, 3)
(1, 2)
(1, 3)
(2, 3)
>>> def pairs(l):
... x = iter(l)
... while True:
... yield x.next(), x.next()
...
>>> for item1, item2 in pairs(l):
... print (item1, item2)
...
(0, 1)
(2, 3)
Hope that clarifies the problem.
Steve
--
You can wordify anything if you just verb it.
- Bucky Katt, Get Fuzzy
More information about the Python-list
mailing list