Philipp
Philipp

Reputation: 415

How do add items from a list in an iterative fashion to two different lists?

I have a time-series consisting of numeric data points, say in form of a list:

x = [924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4]

I need to populate these two lists:

x_list = []
y_list = []

following these three steps:

  1. The first two values from the list, x[0] and x[1], namely 924 and -5, should be added to these two lists below, respectively.
  2. The second aim is to take the next two values or "pairs" of the list, namely x[1] and x[2], and add them to x_list and y_list, respectively.
  3. Finally, I would like to repeat this step, i.e., adding x[2] to x_list and x[3] to y_list and so on, until the end of the time-series x is reached.

I assume that I have to program a function using def. But I don't understand how to set up the code for this aim. Here is the current state of my code.

import numpy as np
import matplotlib.pyplot. as plt

x = [924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4]

x_results = []
y_results = []

for t in Timeseries:
next_n = # This is where I am stuck, struggling to find the correct code
next_y = 
x_results.append(next_x)
y_results.append(next_y)

plt.plot(x_results, y_results, "bo")
plt.show()

Upvotes: 2

Views: 75

Answers (2)

mozway
mozway

Reputation: 262634

for python ≥ 3.10, this is the job of itertools.pairwise:

from itertools import pairwise
x, y = zip(*pairwise(mylist))

output:

x
(924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5),

y
(-5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4)

for python < 3.10, the recipe for pairwise is:

from itertools import tee

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

Upvotes: 1

C.Nivs
C.Nivs

Reputation: 13136

You can use two slices:

mylist = [924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4]

x_list = mylist[:-1]
y_list = mylist[1:]

Upvotes: 3

Related Questions