473,804 Members | 3,674 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pairs from a list

I want to generate sequential pairs from a list.
Here is a way::

from itertools import izip, islice
for x12 in izip(islice(x,0 ,None,2),islice (x,1,None,2)):
print x12

(Of course the print statement is just illustrative.)
What is the fastest way? (Ignore the import time.)

Thanks,
Alan Isaac
Jan 22 '08 #1
18 3812
Alan Isaac <ai****@america n.eduwrites:
(Of course the print statement is just illustrative.)
What is the fastest way? (Ignore the import time.)
You have to try a bunch of different ways and time them. One
idea (untested):

def pairs(seq):
while True:
yield (seq.next(), seq.next())
Jan 22 '08 #2
On Jan 21, 10:20 pm, Alan Isaac <ais...@america n.eduwrote:
I want to generate sequential pairs from a list.
Here is a way::

from itertools import izip, islice
for x12 in izip(islice(x,0 ,None,2),islice (x,1,None,2)):
print x12

(Of course the print statement is just illustrative.)
What is the fastest way? (Ignore the import time.)
Look up the timeit module and test yourself the various alternatives;
that's the most reliable way to tell for sure.

George
Jan 22 '08 #3
On Jan 22, 3:20 am, Alan Isaac <ais...@america n.eduwrote:
I want to generate sequential pairs from a list.
<<snip>>
What is the fastest way? (Ignore the import time.)
1) How fast is the method you have?
2) How much faster does it need to be for your application?
3) Are their any other bottlenecks in your application?
4) Is this the routine whose smallest % speed-up would give the
largest overall speed up of your application?

- Paddy.
Jan 22 '08 #4
On Jan 22, 12:15 am, Paddy <paddy3...@goog lemail.comwrote :
On Jan 22, 3:20 am, Alan Isaac <ais...@america n.eduwrote:I want to generate sequential pairs from a list.
<<snip>>
What is the fastest way? (Ignore the import time.)

1) How fast is the method you have?
2) How much faster does it need to be for your application?
3) Are their any other bottlenecks in your application?
4) Is this the routine whose smallest % speed-up would give the
largest overall speed up of your application?
I believe the "what is the fastest way" question for such small well-
defined tasks is worth asking on its own, regardless of whether it
makes a difference in the application (or even if there is no
application to begin with). Just because cpu cycles are cheap these
days is not a good reason to be sloppy. Moreover, often the fastest
pure Python version happens to be among the most elegant and concise,
unlike other languages where optimization usually implies obfuscation.

George
Jan 22 '08 #5
On Jan 22, 3:20*am, Alan Isaac <ais...@america n.eduwrote:
I want to generate sequential pairs from a list.
Here is a way::

* * from itertools import izip, islice
* * for x12 in izip(islice(x,0 ,None,2),islice (x,1,None,2)):
* * * * print x12

(Of course the print statement is just illustrative.)
What is the fastest way? (Ignore the import time.)

Thanks,
Alan Isaac
Don't know the fastest, but here's a very concise way:

from itertools import izip

def ipairs(seq):
it = iter(seq)
return izip(it, it)
>>list(pairs(xr ange(10)))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>list(pairs('h ello'))
[('h', 'e'), ('l', 'l')]

--
Arnaud

Jan 22 '08 #6
I suppose my question should have been,
is there an obviously faster way?
Anyway, of the four ways below, the
first is substantially fastest. Is
there an obvious reason why?

Thanks,
Alan Isaac

PS My understanding is that the behavior
of the last is implementation dependent
and not guaranteed.

def pairs1(x):
for x12 in izip(islice(x,0 ,None,2),islice (x,1,None,2)):
yield x12

def pairs2(x):
xiter = iter(x)
while True:
yield xiter.next(), xiter.next()

def pairs3(x):
for i in range( len(x)//2 ):
yield x[2*i], x[2*i+1],

def pairs4(x):
xiter = iter(x)
for x12 in izip(xiter,xite r):
yield x12
Jan 22 '08 #7
On Jan 22, 1:19*pm, Alan Isaac <ais...@america n.eduwrote:
[...]
PS My understanding is that the behavior
of the last is implementation dependent
and not guaranteed.
[...]
def pairs4(x):
* * xiter = iter(x)
* * for x12 in izip(xiter,xite r):
* * * * yield x12
According to the docs [1], izip is defined to be equivalent to:

def izip(*iterables ):
iterables = map(iter, iterables)
while iterables:
result = [it.next() for it in iterables]
yield tuple(result)

This guarantees that it.next() will be performed from left to right,
so there is no risk that e.g. pairs4([1, 2, 3, 4]) returns [(2, 1),
(4, 3)].

Is there anything else that I am overlooking?

[1] http://docs.python.org/lib/itertools-functions.html

--
Arnaud
Jan 22 '08 #8
On Jan 22, 1:19*pm, Alan Isaac <ais...@america n.eduwrote:
I suppose my question should have been,
is there an obviously faster way?
Anyway, of the four ways below, the
first is substantially fastest. *Is
there an obvious reason why?
Can you post your results?

I get different ones (pairs1 and pairs2 rewritten slightly to avoid
unnecessary indirection).

====== pairs.py ===========
from itertools import *

def pairs1(x):
return izip(islice(x,0 ,None,2),islice (x,1,None,2))

def pairs2(x):
xiter = iter(x)
while True:
yield xiter.next(), xiter.next()

def pairs3(x):
for i in range( len(x)//2 ):
yield x[2*i], x[2*i+1],

def pairs4(x):
xiter = iter(x)
return izip(xiter,xite r)

def compare():
import timeit
for i in '1234':
t = timeit.Timer('l ist(pairs.pairs %s(l))' % i,
'import pairs; l=range(1000)')
print 'pairs%s: %s' % (i, t.timeit(10000) )

if __name__ == '__main__':
compare()
=============== ======

marigold:python arno$ python pairs.py
pairs1: 0.789824962616
pairs2: 4.08462786674
pairs3: 2.90438890457
pairs4: 0.536775827408

pairs4 wins.

--
Arnaud

Jan 22 '08 #9
Arnaud Delobelle wrote:
According to the docs [1], izip is defined to be equivalent to:

def izip(*iterables ):
iterables = map(iter, iterables)
while iterables:
result = [it.next() for it in iterables]
yield tuple(result)

This guarantees that it.next() will be performed from left to right,
so there is no risk that e.g. pairs4([1, 2, 3, 4]) returns [(2, 1),
(4, 3)].

Is there anything else that I am overlooking?

[1] http://docs.python.org/lib/itertools-functions.html

<URL:http://bugs.python.org/issue1121416>

fwiw,
Alan Isaac
Jan 22 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
4721
by: Equis Uno | last post by:
Hi, Assume I'm given a 100k file full of key-value pairs: date,value 26-Feb-04,36.47 25-Feb-04,36.43 24-Feb-04,36.30 23-Feb-04,37.00 20-Feb-04,37.00
12
7018
by: Steven Bethard | last post by:
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, l) 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
7
5374
by: Woodster | last post by:
Further to a question I posted here recently about coding an xml rpeort parser, I need to use a list of name/value pairs, in this case, a list property names and values for a given tag. Rather than deriving a linked list class and adding in 2 char * to the derived class, I have decided to try and start using templates howver not having used templates before I do not know where to start. Unfortunately time is not on my side and I was...
5
1739
by: Bosconian | last post by:
I need a comma delimited regular expression pattern with the followng restrictions: no leading and trailing white space no trailing comma double quoted numeric/alpha pairs each pair on a separate line For example:
2
1788
by: Evan | last post by:
Is there a simple way to to identify and remove matching pairs from 2 lists? For example: I have a= b=
4
1840
by: Ronald S. Cook | last post by:
I want to maintain a list of value/pairs in my Windows application. Where is the best way to store this? Do I want to use Application Settings and have a row for each value pair? There will be approx 10 of them... like a server name/server IP. I want to be able to bring up those values in a list for a user to choose to connect to a different server. Thanks, Ron
3
1730
by: Gabriel Zachmann | last post by:
Well, could some kind soul please explain to me why the following trivial code is misbehaving? #!/usr/bin/python lst = s =
7
2223
by: tmitt | last post by:
Hi, I missed a couple classes due to being sick this past week and I am having trouble getting steered in the right direction for my programming assignment. I'd ask the professor for help but he has a total of four hours during the week for office hours, all of which I have a class. But anyways... Write a C program that produces prime pairs. At the start, user is prompted to input a positive integer less than 100,000 after which the program...
15
2453
by: mcjason | last post by:
I saw something interesting about a grid pair puzzle problem that it looks like a machine when you find each that work out the way it does and say with all the others that work out the way they do together overlapping common pieces but say connected each working out as connected, but together as connected it's connected with the others connected. a whole machine where connected together is a condition of the machine together as...
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10562
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10303
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.