Splitting list of strings based on a character in each string ( Python )

Tags: , , , ,



So i have a list of strings that looks like this :

my_list = ['389.3K', '2M' , '1.9M' , '6.9M' , '4.3M' , '251.5K' , '3.6M']

This is how the list is generated and made readable (“video” is a list of selenium webelements ) :

my_list = [x.text for x in video]
video.extend(my_list)
my_list = [i for i in my_list if i if not 'ago' in i]
my_list = [w.replace("Views", "") for w in my_list]

What i want to do is SPLIT this list into two other lists based on ONE specific character in each element like so :

k_list = ['389.3K' , '251.5K']

m_list = ['2M' , '1.9M' , '6.9M' , '4.3M' , '3.6M']

My end goal is to be able to have only the numbers in the elements as a float and multiply each element by their appropriate amount ( K = *1000 and M = *1000000 ) like :

my_new_list = ['389,300' , '2,000,000‬' , '1,900,000' , '6,900,000‬' , '4,300,000', '251,500' , '3,600,000‬']

I’m new to python (coding in general tbh) so please excuse any spaghetti code or bad thought process.

This is what i tried :

k_val = "K"
m_val = "M"

if any(k_val in s for s in my_list):
    my_list = [w.replace("K", "") for w in my_list]
    my_list = [float(i) for i in vmy_list]
    my_list = [elem * 1000 for elem in my_list]
elif any(m_val in x for x in my_list):
    my_list = [w.replace("M", "") for w in my_lists]
    my_list = [float(i) for i in my_list]
    my_list = [elem * 1000000 for elem in my_list]

I get :

ValueError: could not convert string to float: ‘2M ‘

Answer

As your input data are already repesenting float values I suggest to harness scientific-notation combined with float following way:

my_list = ['389.3K', '2M' , '1.9M' , '6.9M' , '4.3M' , '251.5K' , '3.6M']
e_list = [i.replace('K','e3').replace('M','e6') for i in my_list]
values = [float(i) for i in e_list]
my_new_list = [f'{int(i):,}' for i in values]
print(my_new_list)

Output:

['389,300', '2,000,000', '1,900,000', '6,900,000', '4,300,000', '251,500', '3,600,000']


Source: stackoverflow