Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round the float after converting from string till second last entry in a list

Tags:

python

list

Assume we have a list:

list_t = ['1.234', '3.6654', '7.134123', '2.2323', 'Someone']

our operation should change the above list of string to float value with rounding the float value till 2 points except the last string.

expected output will be:

list_t = [1.23, 3.67, 7.13, 2.23, 'Someone']
like image 406
SomeOne Avatar asked Feb 02 '26 11:02

SomeOne


1 Answers

If the string is always present in the last index, you can use this simple list comprehension:

list_t = ['1.234', '3.6654', '7.134123', '2.2323', 'Someone']

list_t = [round(float(num),2) for num in list_t[:-1]] + [list_t[-1]]

print(list_t)

Output:

[1.23, 3.67, 7.13, 2.23, 'Someone']

If the string can be at any position, you don't have to use a try-except block or something. You can use this list comprehension:

list_t = ['1.234', '3.6654', '7.134123', '2.2323', 'Someone']

list_t = [round(float(num),2) if num.replace('.', '', 1).isdigit() else num for num in list_t]

print(list_t)

Output:

[1.23, 3.67, 7.13, 2.23, 'Someone']
like image 163
Sushil Avatar answered Feb 04 '26 01:02

Sushil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!