brium-brium
brium-brium

Reputation: 837

Getting list of middle values in between values of list

I have a list of values: [0,2,3,5,6,7,9] and want to get a list of the numbers in the middle in between each number: [1, 2.5, 4, 5.5, 6.5, 8]. Is there a neat way in python to do that?

Upvotes: 3

Views: 312

Answers (6)

B. M.
B. M.

Reputation: 18628

[(l[i]+l[i+1])/2 for i in range(len(l)-1)]

Upvotes: 0

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

values = [0,2,3,5,6,7,9] 
middle_values = [(values[i] + values[i + 1]) / 2.0 for i in range(len(values) - 1)]

Dividing by 2.0 rather than 2 is unnecessary in Python 3, or if you use from __future__ import division to change the integer division behavior.

The zip or itertools.izip answers are more idiomatic.

Upvotes: 1

Sam Chats
Sam Chats

Reputation: 2321

Simple for loop:

nums = [0,2,3,5,6,7,9]
betweens = []
for i in range(1, len(nums)):
    if nums[i] - nums[i-1] > 1:
        betweens.extend([item for item in range(nums[i-1]+1, nums[i])])
    else:
        betweens.append((nums[i] + nums[i-1]) / 2)

Output is as desired, which doesn't need further conversion (in Python3.x):

[1, 2.5, 4, 5.5, 6.5, 8]

Upvotes: 0

Gabriel
Gabriel

Reputation: 41

Use a for loop:

>>> a = [0,2,3,5,6,7,9]
>>> [(a[x] + a[x + 1])/2 for x in range(len(a)-1)]
[1.0, 2.5, 4.0, 5.5, 6.5, 8.0]

However using zip as @Chris_Rands said is better... (and more readable ¬¬)

Upvotes: 3

Aran-Fey
Aran-Fey

Reputation: 43136

Obligatory itertools solution:

>>> import itertools
>>> values = [0,2,3,5,6,7,9]
>>> [(a+b)/2.0 for a,b in itertools.izip(values, itertools.islice(values, 1, None))]
[1.0, 2.5, 4.0, 5.5, 6.5, 8.0]

Upvotes: 1

Chris_Rands
Chris_Rands

Reputation: 41168

It's a simple list comprehension (note I'm asuming you want all your values as floats rather than a mixture of ints and floats):

>>> lst = [0,2,3,5,6,7,9] 
>>> [(a + b) / 2.0 for a,b in zip(lst, lst[1:])]
[1.0, 2.5, 4.0, 5.5, 6.5, 8.0]

(Dividing by 2.0 ensure floor division is not applied in Python 2)

Upvotes: 5

Related Questions