I am looping through variables of the form - V15_1_1. The middle and last number in this string changes for each variable. I want to create a string of all the unique middle numbers. For example, I may have V15_1_1, V15_2_3, V15_2_6, V15_12_17,V15_12_3 which would return a text string of '1,2,12'
Here you go:
my_list = ['V15_1_1', 'V15_2_3', 'V15_2_6', 'V15_12_17','V15_12_3']
def unique_middle_values(input_list):
return set([i.split('_')[1] for i in input_list])
unique_middle_values(my_list)
{'1', '12', '2'}