Home > Net >  Retrieve values after last underscore using python as a list
Retrieve values after last underscore using python as a list

Time:12-28

I am trying to fetch the list off students to get the integers from the array

Input:

list=['table_name_student_1', 'table_name_student_20', 'table_name_student_300', 'table_name_student_4500']

Expected Output: [1,20,300,4500]

I tried split function but I am not able to use it in a list

table_name = 'table_name_student_12345'
id = table_name.split('_')
print(id) -- #Output: 12345

CodePudding user response:

You can use split and int in a list comprehension:

lst = ['table_name_student_1', 'table_name_student_20', 'table_name_student_300', 'table_name_student_4500']

output = [int(x.split('_')[-1]) for x in lst]
print(output) # [1, 20, 300, 4500]

CodePudding user response:

Prev. post works perfectly, here is just a regex version for reference:

Note - don't use list or id as the variable name. It's a Python built-in.

import re

for x in L:                        # L is your list
    num = map(int, re.findall(r'\d ', x))
    result.extend(list(num))

    
result
[1, 20, 300, 4500]

CodePudding user response:

list=['table_name_student_1', 'table_name_student_20', 'table_name_student_300', 'table_name_student_4500']
result = []

for element in list:
    result.append(element.split('_')[-1])

print(result)`    

try this it worked for me

CodePudding user response:

The easiest way would be to create a function that splits the string according to a symbol, which is _ in your case.


def retrieve_int_value(element):
    splitted=element.split('_')
    value = splitted[-1]
    return value

students_list = ['table_name_student_1', 'table_name_student_20', 'table_name_student_300', 'table_name_student_4500']
values_list = []

for element in students_list:
    value = int(retrieve_int_value(element))
    values_list.append(value)
print(values_list)

Output: [1, 20, 300, 4500]

  • Related