How can i multiply only items in list which has some common numbers at the end?

Viewed 38

I have a list

sample_list=[-1.0, -1.0, 1.25999, 3999.0, 6999.0, 3777.0, 6888.0, 3999.0, 3999.0, 6999.0, 6999.0, 8999.0, 14.75999]

I have to find only those items which contains "999" then trim "999" from that item and then multiply with 30.

Example : if 1.25999 is the item then removing "999" ->1.25 then multiply it with 30 resulting 37.5

I have tried following code snippet:

sample_list=[-1.0, -1.0, 1.25999, 3999.0, 6999.0, 3777.0, 6888.0, 3999.0, 3999.0, 6999.0, 6999.0, 8999.0, 14.75999]
for i in sample_list:
    if "999" in i:
        i = i.translate(None, '999')
        i=i*30
print(sample_list)

I am getting error : TypeError: argument of type 'float' is not iterable

4 Answers

You could do this in one line, thus also modifying the list itself:

sample_list = [-1.0, -1.0, 1.25999, 3999.0, 6999.0, 3777.0,
               6888.0, 3999.0, 3999.0, 6999.0, 6999.0, 8999.0, 14.75999]
sample_list = [float(str(i).replace('999', ''))*30 if '999' in str(i) else i for i in sample_list]
print(sample_list)

What it does:
In order to check if a number is within another number, we must first convert them to strings since that way you can use the in keyword.
Next we check if 999 is in the number.
If it is, we remove the 999, convert it back to a number and multiply by 30.
If it isn't, we just enter the number regularly.

This gives us a list without 999s and multiplied where it was removed.

If you'd like to know more about the one-liner format, they're called list comprehensions and you can read more about them here.

k=[]
sample_list=[-1.0, -1.0, 1.25999, 3999.0, 6999.0, 3777.0, 6888.0, 3999.0, 3999.0, 6999.0, 6999.0, 8999.0, 14.75999]
for i in sample_list:
        if "999" in str(i):
            i=str(i).replace('999','')
            k.append(float(i)*30)
        else:
            k.append(float(i))

#output
[-1.0, -1.0, 37.5, 90.0, 180.0, 3777.0, 6888.0, 90.0, 90.0, 180.0, 180.0, 240.0, 442.5]

You can iterate the numbers, convert to string then check if 999 is there if yes replace it by empty string value then finally convert to float and multiply by 30, you can accomplish it using List Comprehension. And to avoid multiple conversions, you can use named expression := if you have python 3.9+:

>>>[float(v.replace("999", ""))*30 if "999" in (v:=str(x)) else x for x in sample_list]
# Output
[-1.0, -1.0, 37.5, 90.0, 180.0, 3777.0, 6888.0, 90.0, 90.0, 180.0, 180.0, 240.0, 442.5]

The question mentions "common numbers at the end". Therefore, to isolate those values one could do this:

sample_list = [-1.0, -1.0, 1.25999, 3999.0, 6999.0, 3777.0, 6888.0, 3999.0, 3999.0, 6999.0, 6999.0, 8999.0, 14.75999]
output = [float(e[:-3])*30 if (e := str(n)).endswith('999') else n for n in sample_list]
print(output)

Output:

[-1.0, -1.0, 37.5, 3999.0, 6999.0, 3777.0, 6888.0, 3999.0, 3999.0, 6999.0, 6999.0, 8999.0, 442.5]
Related