-2

I am trying to fetch the list of students to get the integers from an 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 the 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
Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
Sara
  • 33
  • 5

3 Answers3

3

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]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
2
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

SLOWDEATH
  • 31
  • 5
2

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]

ivey221
  • 95
  • 7