Andrew Chey
Andrew Chey

Reputation: 21

Padding a List of Tuples With (0, 0)s Using an Index List

I am relatively new to python and have a problem where I want to write a code to efficiently pad a list with tuples of (0, 0) using an index list that gives the positions for the known data elements. Here is my given data and what I wish to accomplish.

What I am given:

time = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data_time = [2, 3, 4, 7, 8]
data = [(41, 53), (89, 5), (42, 78), (81, 27), (21, 36)]

What I wish to accomplish

data_mod = [
    (0, 0), (41, 53), (89, 5), (42, 78), (0, 0),
    (0, 0), (81, 27), (21, 36), (0, 0), (0, 0)
]

Basically, I want to pad the list data to the length of the list time, using the list data_time as an index for the elements of data.

Upvotes: 0

Views: 819

Answers (2)

tavnab
tavnab

Reputation: 2734

While not the most pythonic, this is a twist on the merge algorithm for 2 sorted lists, except with substitution from your data list.

time = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data_time = [2,3,4,7,8]
data = [(41,53), (89, 5), (42, 78), (81, 27), (21, 36)]

i = 0
j = 0
result = []

while i < len(time) and j < len(data_time):
  if time[i] < data_time[j]:
    # found a gap; pad & advance the index for 'time'
    result.append((0,0))
    i += 1
  elif time[i] > data_time[j]:
    # found a gap; pad & advance the index for 'data_time'
    result.append((0,0))
    j += 1
  else:
    # found a match; include it & advance both indices
    result.append(data[j])
    i += 1
    j += 1

# if there are more entries in 'time', add the needed padding
result += [(0, 0)] * (len(time) - i)

print result

Output:

[(0, 0), (41, 53), (89, 5), (42, 78), (0, 0), (0, 0), (81, 27), (21, 36), (0, 0), (0, 0)]

Upvotes: 0

user94559
user94559

Reputation: 60143

Take a look and let me know if you have questions:

time = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data_time = [2,3,4,7,8]
data = [(41,53), (89, 5), (42, 78), (81, 27), (21, 36)]

# start with all (0, 0)s
data_mod = [(0, 0)] * len(time)

# take indices from data_time and values from data
for index, value in zip(data_time, data):
    # overwrite the value in the right place
    # indices appear to be 1-based instead of 0-based
    data_mod[index - 1] = value

print(data_mod)

# Output:
# [(0, 0), (41, 53), (89, 5), (42, 78), (0, 0), (0, 0), (81, 27), (21, 36), (0, 0), (0, 0)]

Upvotes: 2

Related Questions