Append list in list of lists

I have a list of lists like this.

lst=[[0, 0.05],
 [1, 0.02],
 [3, 0.02],
 [5, 0.01]]

I want to add the missing lists in the list to get this.

lst=[[0, 0.05],
 [1, 0.02],
 [2, 0.01],
 [3, 0.01],
 [4, 0.005],
 [5, 0.005]]

Here, [2,x2] added between [1,x1] and [3,x3] and x2=x3/2 and x3=x2 is performed. Same is to be done for [4, x4].

I have tried this.

for i in range(len(lst)):
    if lst[i][0]!=i:

This code is unable to keep track of the element being iterated and adds duplicates and wrong values.

Since you have only one missing value at once, this should work:

lst=[[0, 0.05],
 [1, 0.02],
 [3, 0.02],
 [5, 0.01]]

finlst = [lst[0]]
for ll in lst[1:]:
    lind = finlst[-1][0]
    if ll[0] - lind == 1:
        finlst.extend([[lind+1, ll[1]/2], [lind+2, ll[1]/2]])

finlst is: [[0, 0.05], [1, 0.02], [2, 0.01], [3, 0.01], [4, 0.005], [5, 0.005]].

And since we are here, I propose a more general solution working also in case where there is more than one missing value.

finlst = [lst[0]]
for ll in lst[1:]:
    lastind = finlst[-1][0]
    toadd = ll[0] - lastind
    for i in range(toadd):
        finlst.append([lastind+i+1, ll[1]/toadd])

Append vs Extend in Python Lists, Adding Elements to a List. Lists are one of the most useful data structures available in Python, or really any programming language, since they're used in so� Append list elements to list of lists in python. Ask Question Asked 3 years ago. Active 3 years ago. Viewed 3k times 1. 1. Given the following lists: list1 = [[1, 2

You could do this with a list comprehension:

r=lst[:1]+[[k+1,v/(j-i)] for (i,_),(j,v) in zip(lst,lst[1:]) for k in range(i,j)]
print(r) # [[0, 0.05], [1, 0.02], [2, 0.01], [3, 0.01], [4, 0.005], [5, 0.005]]

Or using procedural code:

r = lst[:1]
for j,v in lst[1:]:
    i = r[-1][0]
    for k in range(i,j):

Appending items to a list of lists in python, Python lists are mutable objects and here: plot_data = [[]] * len(positions). you are repeating the same list len(positions) times. >>> plot_data� I'm having issues appending data to a list which is already in a list format. I have a program which will export results objects during a simulation loop. The data itself is stored as a list of mat

It may not be how you want to do it exactly but I am going to propose a slight deviation to your code.

What about :

mydict = {0: 0.05,
          1: 0.02,
          3: 0.02,
          5: 0.01}
for i in range(max(mydict.keys()) - 1, min(mydict.keys()), -1):
    if i not in mydict.keys():
        mydict[i] = mydict[i + 1] / 2
        mydict[i + 1] = mydict[i + 1] / 2
lst = sorted(map(list, mydict.items()))

Python lists - working with lists in Python, This section will show how elements are added to a Python list. #!/usr/ bin/env python # langs = [] langs.append("Python")� Python – Append List to Another List – extend() Syntax – extend() Following is the syntax of extend() function. list1.extend(list2) where elements of list2 are appended to the elements of Example 1: Append a list to another list. Example 2: Append a list to another list keeping a copy of

What fits properly for your question is most probably interpolation.

If you want a liniar regression (at the cost of losing accuracy) a piece of code could look like this:

 elementsToAdd = list(set([i for i in range(0, lst[-1][0] + 1]) - set([i[0] for i in lst]))

 for e in lst:
    if (e[0] - 1) in elementsToAdd:
       lst.append([(e[0] - 1), e[1] / 2.0]

 lst.sort(key = (lambda x: x[0]))

Add an item to a list in Python (append, extend, insert), Add an item to the end: append() Combine lists: extend() , + operator. Add an item at specified index: insert() Add another list or tuple at specified index: slice. In Python, use list methods append(), extend(), and insert() to add items to a list or combine other lists. You can also use the + operator to combine lists, or use slices to insert itemss at specific positions. Add an item to the end: append() Combine lists: extend(), + operator; Add an item at specified index: insert()

Just build your logic during iteration. I added the ability to handle gaps bigger than 1, but regardless, the code should work just fine either ways.

lst=[[0, 0.05],
 [1, 0.02],
 [3, 0.02],
 [5, 0.01]]

prev_idx, prev_val = lst[0] #keeps track of last idx and value seen
result = [[prev_idx, prev_val]]

for idx, val in lst[1:]:
    if (idx - prev_idx) == 1: #no gap, just add values as is
        result.append([idx, val])
        steps_to_add = idx - prev_idx
        gap_to_fill = (val)/steps_to_add
        for i in range(prev_idx + 1, idx + 1): #iterate and fill upto current idx
            result.append([i, gap_to_fill])        
    prev_idx, prev_val = idx, val

[[0, 0.05], [1, 0.02], [2, 0.01], [3, 0.01], [4, 0.005], [5, 0.005]]

How to construct a list of lists in Python, How to construct a list of lists in Python. Use list.append(). Use a list comprehension. Constructing a list of lists creates a list with another list as each of its� This method adds an element at the end of an existing list. The syntax to use it is: a.append(x) Here the variable a is our list, and x is the element to add. This expression is equivalent to a[len(a):] = [x]. For example, here is how to use it to place the element "y" at the end of our list, a: a = [1, 'x', 2] a.append('y') print(a)

Python Lists | Python Education, The "empty list" is just an empty pair of brackets [ ]. The '+' works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4]� You just need to use list’s append method to create list of lists. Here is simple example to create list of lists in Python. list1= [1,2,3,4] list2= [5,6,7,8] listoflists= [] listoflists.append (list1) listoflists.append (list2) print ("List of Lists:",listoflists)

How to join list of lists in python?, There are different ways to flatten a list of lists. to flat list object. L1=[[1,2],[3,4,5], [6,7,8,9]] flat=[] for i in L1: for j in i: flat.append(j) print (flat). Use list.extend () to convert a list of lists to a flat list. In python list data type provides a method to add all the contents of an iterable to the existing list, list.extend(iterable) list.extend (iterable) list.extend (iterable) It extends the existing list object by appending all the contents of given iterable.

Python List append(), The item can be numbers, strings, dictionaries, another list, and so on. Return Value from append(). The method doesn't return any value (returns None ). Example� Other Ways to Extend a List. You can also append all elements of an iterable to the list using: 1. the + operator. a = [1, 2] b = [3, 4] a += b # a = a + b # Output

  • What about adding the lists and then sorting them with: sorted(lst, key=lambda x: x[0])
  • Can you explain the logic for the second value on each row and why the value of the existing [3, 0.02] entry changes to [3, 0.01] in your expected result.
  • How do I add the lists though ? The 2nd value in each list depends on the next value (half of it). The next value then becomes same as the previous one. Simply put, any missing list shares the value of the next list uniformly.
  • @AlainT. hope the previous comment answered your question.
  • You will always skip one value only? Or you can have something like [[1, 0.4], [5, 04]]?
  • I think you want finlst.append([lastind+i+1, ll[1] / (2**(toadd-i))])
  • @Ashargin No, why? I should divide the value ll[1] for the number of extra list created, which is simply toadd.
  • This worked on my actual input list. So, I'll go for this for now.
  • @Valentino it is not clear what the user wants for when gaps are wider than only 1 row at once. From my understanding the *2 factor had to be repeated but nothing is clearly said for that case so your guess is as good as mine if not better
  • @Ashargin it seems he wants half the value because he's dealing with lists where only one element is missing. Sort of normalization. Hence in a more general case, I divide by the number of list added +1, which is toadd. That's what I thought.
  • Well, I don't have a missing list. It has to be derived.
  • Let me try to derive the missing list and then use your method.
  • you can also use something like Just trying to get working myself, e.g. insert nan when the value is missing and then you'll be able to apply a mask and replace the nan with the value you want
  • This is not what the user wants, you're sorting along axis 0 for each column independantly and there is no reason that it would be equal to the rule the user wants to implement