I have the following lists in python
lista_x = [2,3,4,5]
lista_y = [6,7,8,9]
I try to replicate the current element (excluding the ends) to the next position. So you get something similar to this:
lista_x = [2,3,3,4,4,5]
lista_y = [6,7,7,8,8,9]
I have this code, but I could not achieve my goal
for i in range(len(lista_x)):
if(i != 0 and i!=len(lista_x)): #Exluyendo extremos
lista_x.insert(i,lista_x[i]) #Agrega el valor actual
lista_y.insert(i,lista_y[i])
This question looks like it is an exercise that seeks to obtain an ingenious solution to the problem posed.
In general, when you have to process a list, the first thing you should know are the different methods and functions that operate with lists and see if any of them can be useful to you. One of the most powerful is zip with which you can mix lists. With a little insight, you can see that if you do a
zip
list with itself, you can come up with something very close to what you need:The result:
What is missing is to concatenate all those tuples and you would get the solution. To concatenate you could create a loop that adds each tuple, but there is another more direct way using the function
sum
:The initial element is the empty tuple
()
to which the tuples that we obtain through are concatenated (adding)zip
to obtain a tuple. Since we are asked for a list, we will have to convert the tuple to a list .Putting everything in its place, the solution is:
To keep things simple, create a function that iterates through the list from the second position to the last position. This is done by enclosing after the list in braces
[1:-1]
. What this syntax denotes is that the list is copied from the second position to the end, excluding the last item.Remember that in Python the indices start from the
0
, so the second position is the1
.He
-1
would be the last positionUsing the method
append
Using the method
insert
Using
sum
over tuples generated from an iterationThank you very much, your method worked for me. But I also found in English stack overflow a function that solved it. In case someone gets to use this one day, I'll leave it here.
Why not use the repeat function from the numpy library