Question

I wanted to see if there was a better way of doing the following:

I have a list of strings which may actually be floats, letters and other characters like "-" and "*":

mylist = ["34.59","0.32","-","39.29","E","0.13","*"]

I was to create a new list which iterates through mylist and checks IF an item is greater than 0.50, if it is, then that item should be rounded to the nearest whole number, if not, then it should be left alone and appended to the new list.

Here is what I have, this works but I wanted to know if there is a better way of doing it:

for item in mylist:
    try:
        num = float(item) 
        if num > 0.50:
            newlist.append(str(int(round(num))))
        else:
            newlist.append(item)
    except ValueError:
        newlist.append(item)

print newlist

Output:

['35', '0.32', '-', '39', 'E', '0.13', '*']

What do you guys thing?

Was it helpful?

Solution 2

How about make a function?

def round_gt_05(x):
    try:
        num = float(x)
        if num > 0.5:
            return str(int(round(num)))
    except ValueError:
        pass
    return x

mylist = ["34.59","0.32","-","39.29","E","0.13","*"]
newlist = map(round_gt_05, mylist)
print newlist

OTHER TIPS

If the values in your list can be separated by x[0].isdigit(), you can use a list comprehension. This means there will not be a '' or '2E' or '-3' or '.35' in your list.

>>> [str(int(round(float(x)))) if x[0].isdigit() and float(x) > 0.50 else x for x in mylist] 
['35', '0.32', '-', '39', 'E', '0.13', '*']
>>> 

You could try this also.

def isfloatstring(instr):
    try:
         float(instr)
    except ValueError:
         return False
    return True


[str(int(round(float(n)))) if isfloatstring(n) and float(n) > 0.5 else n for n in listtemp]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top