Drew Verlee
Drew Verlee

Reputation: 1900

Create a list where each element is a created based on the index of a nested list in python

For example

alist = [[1,2],[10,10],[5,5]]

I want to create a new list that has the average of each lists[nth] element and the lists[n+1] element. where n is the size of the list. I want the it have the behaviour you would expect from the step in range([start],stop,[step]), if the step was 2.

so working backwards from the desired output

output = [[5.5,6],[5,5]]

output = [[(1 + 10)/2 , (2 + 10)/2], [5,5]] # The last list has no matching list, so it remains unchanged

output = [[(alist[0][0] + alist[1][0]) / 2, (alist[0][1] + alist[1][1]) / 2), alist[2],alist[2]

output = alist[nth ][yth] + alist[n + 1][y + 1] ....

I went down several roads attempting to make this work and never hit upon a solution. I feel like something in the iterators module should be helpful.

Any suggestions?

Upvotes: 0

Views: 76

Answers (2)

John La Rooy
John La Rooy

Reputation: 304503

>>> [[(x+y)*.5  for x,y in zip(*item)] for item in zip(alist, alist[1:])]
[[5.5, 6.0], [7.5, 7.5]]

You can do a more memory efficient version with itertools

>>> from itertools import izip, islice
>>> [[(x+y)*.5  for x,y in izip(*item)] for item in izip(alist, islice(alist,1,None))]
[[5.5, 6.0], [7.5, 7.5]]

EDIT: Still not certain what the OP wants for the general cases, but here are a couple of alternatives

>>> alist = [[1,2],[10,10],[5,5]]
>>> if len(alist)%2:
...     alist.append(alist[-1])
... 
>>> [[(x+y)*.5  for x,y in zip(*item)] for item in zip(alist, alist[1:])]
[[5.5, 6.0], [7.5, 7.5], [5.0, 5.0]]
>>> [[(x+y)*.5  for x,y in zip(*item)] for item in zip(alist[::2], alist[1::2])]
[[5.5, 6.0], [5.0, 5.0]]

Upvotes: 3

nebffa
nebffa

Reputation: 1549

Why not an easily readable version?

alist = [[1,2],[10,10],[5,5]] 
output = []

for i in range(0, len(alist) - 2):
    avg1 = (alist[i][0] + alist[i + 1][0]) / 2.0
    avg2 = (alist[i][1] + alist[i + 1][1]) / 2.0
    output.append([avg1, avg2]) # append averages
output.append([1.0 * j for j in alist[-1])
# append final list as a list of floats ([5.0, 5.0] in this case)

>>> output
[[5.5, 6.0], [5.0, 5.0]]

Upvotes: 0

Related Questions