0

Possible Duplicate:
pairwise traversal of a list or tuple

I have this list: [(0, 'set'), (1, 'of'), (4, 'coloured'),(5, 'eels')]

I would like to efficiently iterate and achieve item+1[0] - item[0]

as in 1 - 0, 4 - 1, 5 - 4

I currently have:

search_list = [(0, 'set'), (1, 'of'), (4, 'coloured')] 
[search_list[i+1][0]-search_list[i][0] for i in range(0,len(search_list)-1)]

But my code is not as efficient as I would like. Can map and lambda achieve the outcome?

I would like to avoid importing modules (but, of course, will if lambda and map cannot achieve this)

Community
  • 1
  • 1
Rich Tier
  • 9,021
  • 10
  • 48
  • 71
  • 2
    I just noticed you asked about a better performing solution. You won't find anything significantly better than what you have unless you use NumPy (specifically, `numpy.diff()`). – Sven Marnach Apr 04 '12 at 13:21
  • The accepted answer in the question that Sven mentions should work here too, you just need to access an element of a tuple as well. – Simeon Visser Apr 04 '12 at 13:25
  • Usually map with lamba is slower than list comprehensions. Also if you are using python 2 use 'xrange' instead of 'range'. That creates generator instead of list. – jamylak Apr 04 '12 at 13:47

1 Answers1

0

I'm not sure about being efficient:

>>> search_list = [(0, 'set'), (1, 'of'), (4, 'coloured'),(5, 'eels')]
>>> [y[0]-x[0] for x,y in zip(search_list,search_list[1:])]
[1, 3, 1]

itertools version by popular demand:

>>> from itertools import izip, islice
>>> search_list = [(0, 'set'), (1, 'of'), (4, 'coloured'),(5, 'eels')]
>>> [y[0]-x[0] for x,y in izip(search_list, islice(search_list, 1, None))]
[1, 3, 1]
Charles Beattie
  • 5,739
  • 1
  • 29
  • 32
  • 1
    You only need to slice once -- the longer list will just have its last item ignored by `zip`. – agf Apr 04 '12 at 13:32
  • thanks. timeit shows: mine at 1000 runs: 0.00149552307798s yours at 1000 runs0.00224554247503s Can the answer be improved based on @agf comment? – Rich Tier Apr 04 '12 at 13:42
  • 1
    @rikAtee Is it actually a bottleneck? If not, don't worry about it. `[y[0]-x[0] for x,y in zip(search_list,search_list[1:])]` should be slightly faster than with the extra slicing, and use less memory, but it rarely matters. If memory useage is important, you can use your version or use `itertools` -- `izip` instead of `zip` and `islice(1, len(search_list))` instead of `search_list[1:]`. – agf Apr 04 '12 at 14:04
  • Mine was only an attempt to make it efficient in terms of easy to read, type and maintain. – Charles Beattie Apr 05 '12 at 11:27