How to duplicate the elements of a list excluding extremes in python

7

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 extremes) to the next position. So 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 have not been able to 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])
    
asked by Carlos Cardoso 26.09.2016 в 00:48
source

4 answers

9

This question has pints of an exercise that seeks to obtain an ingenious solution to the proposed problem.

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 search if any of them can be useful. One of the most powerful is zip with which you can mix lists. With a little insight, you can see that if you make a zip of the list with yourself, you can reach something very close to what you need:

>> lista = [2, 3, 4, 5]
>> resultado = zip(lista, lista[1:])

The result:

>> print(list(resultado))
[(2, 3), (3, 4), (4, 5)]

What is missing is concatenating all those tuples and you would get the solution. To concatenate you could create a loop that was adding each tuple, but there is another more direct way using the function sum :

sum(zip(lista, lista[1:]), ())

The initial element is the empty tuple () to which it is concatenated (adding) the tuples that we obtain by zip to obtain a tuple. As they ask us for a list, we'll have to convert the tuple to a list .

Putting everything in its place, the solution is:

resultado = list(sum(zip(lista, lista[1:]), ()))
    
answered by 26.09.2016 / 01:52
source
5

To not complicate your life, create a function that runs the list from the second position to the last position. This is done by placing after the list between braces [1:-1] . This syntax denotes that the list is copied from the second position to the end, excluding the last item.

Remember that in Python the indexes start from 0 , so the second position is 1 .

The -1 would be the last position

Using the append method

# -*- coding: utf-8 -*-

lista_x = [2, 3, 4, 5]
lista_y = [6, 7, 8, 9]


def no_entiendo_para_que_es_esto(lista):
    resultado = []   # creamos una nueva lista para trabajar
    resultado.append(lista[0])  # agregamos a la lista el primer item

    # recorremos desde la posición 2 hasta la ante ultima posición
    for item in lista[1:-1]:
        # añadimos a la lista dos veces el item actual.
        resultado.append(item)
        resultado.append(item)

    resultado.append(lista[-1])  # agregamos a la lista el ultimo item
    return resultado


print no_entiendo_para_que_es_esto(lista_x)
print no_entiendo_para_que_es_esto(lista_y)

Using the insert method

# -*- coding: utf-8 -*-


def no_entiendo_para_que_es_esto2(lista):

    resultado = lista[:]  # hacemos una copia exacta de la lista original

    # creamos un rango desde el indice 1 hasta el ante último.
    for indice in range(len(lista))[1:-1]:
        # Debemos multiplicar por dos el indice al que queremos insertar el
        # valor, ya que la lista va creciendo y los item moviendose una
        # posicion en cada iteración.
        resultado.insert(indice * 2, lista[indice])

    return resultado


print no_entiendo_para_que_es_esto2(['a', 'b', 'c', 'd', 'e'])
print no_entiendo_para_que_es_esto2(['uno', 'segundo', 'tercero', 'ultimo'])
print no_entiendo_para_que_es_esto2([1, 2, 3, 4, 5, 6, 7])

Using sum on tuples generated from an iteration

def solucion3(lista):
    return sum([(item, item) for item in lista], ())[1:-1]


print solucion3([2, 3, 4, 5])
# (2, 3, 3, 4, 4, 5)

print solucion3([2, 3, 4, 5, 6])
# (2, 3, 3, 4, 4, 5, 5, 6)

print solucion3(['a', 'b', 'c', 'd'])
# ('a', 'b', 'b', 'c', 'c', 'd')

print solucion3(['a', 'b', 'c', 'd', 'c'])
# ('a', 'b', 'b', 'c', 'c', 'd', 'd', 'c')
    
answered by 26.09.2016 в 01:11
2

Thank you very much, your method worked for me. But I also found in English stack overflow a function that solved it. In case someone ever uses this, here I leave it.

lista_x = [i for i in lista_x for _ in (0, 1)] 
lista_y = [i for i in lista_y for _ in (0, 1)]

#Eliminamos el primer elemento y el ultimo (excedentes generado por la funcion anterior)
lista_x.pop(0)
lista_y.pop(0)

lista_x.pop(len(lista_x)-1)
lista_y.pop(len(lista_y)-1)
    
answered by 26.09.2016 в 01:46
0

Why not use the repeat function of the numpy library

import numpy as np
a = [1,2,3,4]                    # una lista cualquiera
b = np.repeat(a,2)               # duplicas la lista
c = np.delete(b,[0,len(b)-1])    # eliminas el primer y último elemento
print c                          # imprimes la lista
[1 2 2 3 3 4]
    
answered by 13.10.2016 в 21:48