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

Viewed 49

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']
4 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']

First i thought to use a list comprehension, but because of a string value, it is not possible.

The other idea here is to initialize a new list, iterate over, use try..except to safely convert to float and round, if exception, then append the whole string, at last assign slice copy:

list_t = ['1.234', '3.6654', '7.134123', '2.2323', 'Someone']
n = []
for x in list_t:
  try:
    y = round(float(x),2)
    n.append(y)
  except:
    n.append(x)
list_t = n[:]
print(list_t)
for index, item in enumerate(list_t):
    if index < len(list_t) - 1:
        list_t[index] = round(float(item),2)

Enumerate gives us the position of each item in a list, along with the item itself
We want to act on every item except the last one. Since python zero-indexes (first item in a list is item 0), we want to go up to the length of the list minus 1.
For each item that meets that criteria, convert it to a float and round it.

If this gets expanded so that there are multiple string entries, the below might be better:

for index, item in enumerate(list_t):
    try:
        list_t[index] = round(float(item),2)
    except ValueError:
        pass

Instead of specifically ignoring the last item of a list, this tries to convert all items, but ignores any that fail due to being the wrong type.

list_t = ['1.234', '3.6654', '7.134123', '2.2323', 'Someone']
for i in range(len (list_t) - 1):
    list_t [i] = round (float (list_t [i]), 2)
print (list_t)
Related