Handling an item in a list in python

0

We need to manipulate an entire element of a list, suppose that in this list it is like this:

List = [123432, 2345321, 234554]

I want to get a new number of the centers of each item from the list I mean that if the number has 5 digits, take the digits from 2 to 4, if it is 7, take the digits from 3 to 5

newList = [234, 453, 345] - the number of digits to take depends on a valiable "k" entered by the user

My only doubt is how I can access half of the integers in the list, it just occurs to me to make a new list for each element, split and manipulate the digits as elements of a litsa, but I still have the doubt if it is a correct way to do it and above all I still have the doubt of how to get those elements in between.

    
asked by Humberto Mendoza 04.02.2017 в 18:26
source

3 answers

0

The concept of this code is to remove the last and the first element of the number, until we get the number "k" of numbers.

lista = [12345, 123456, 1234567]

def central_number(number):
    str_number = str(number)
    sobrantes = len(str_number) - k

    if sobrantes >= 0:
        separate_last_element = True
        for sobrante in range( 0, sobrantes ):
            if separate_last_element:
                str_number = str_number[0:-1]
            else: # Separate the first element
                str_number = str_number[1: ]

            separate_last_element = not separate_last_element

        return int( str_number )

k = 3
print map( central_number, lista  )
k = 4
print map( central_number, lista  )
k = 5
print map( central_number, lista  )
    
answered by 04.02.2017 / 20:30
source
1

You could try this (Python 2.7):

lista = [123432, 2345321, 234554]
nueva_lista = []
k = 3
for num in lista:
    num = str(num) # Lo hago string para poder saber la longitud
    mitad = len(num)/2 - 1 # Saco la mitad
    nueva_lista.append(int(num[mitad : mitad + k])) # Lo agrego a la nueva lista convertido en int

print(nueva_lista)

Output:

[343, 453, 455] 

Note: for Python 3.5 you should modify the following line:

mitad = len(num)//2 - 1 # Saco la mitad

Since in Python 3.5 all divisions return a floating

I hope that it has served you! Greetings

    
answered by 04.02.2017 в 19:03
1

Once you know how to extract half, the rest does not have much problem:

def mitad(s,k):
    m = max((len(s)-k)//2, 0)
    return s[m:m+k]

lista = [123432, 2345321, 234554]
k = 3

nueva_lista = [int(mitad(str(i),k)) for i in lista] 
    
answered by 05.02.2017 в 18:18