2013-07-24 18 views
-2

我想看看是否有这样做的更好的方法如下:回合字符串列表/浮如果大于X

我有一个字符串实际上可能花车,字母和其他字符,如列表“ - ”和‘*’:

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

我是要建立一个新的列表,它通过MYLIST并检查重复。如果一个项目是大于0.50,如果是,那么该项目应被四舍五入到最接近的整数如果没有,那么它应该被单独留下并追加到新列表中。

这里是我,这工作,但我想知道是否有这样做的更好的办法:

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 

输出:

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

你们有什么事吗?

+0

为什么你想要一个更好的方法?这种方法太慢了吗?它占用太多内存吗?或者是别的什么? – 2013-07-24 08:45:33

+0

我不喜欢这个事实,它除了ValueErrors ... –

回答

0

如何制作一个功能?

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 
1

如果在列表中的值可以通过x[0].isdigit()分开,你可以用一个列表理解。这意味着您的列表中不会有'''2E''-3''.35'

>>> [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', '*'] 
>>> 
0

你也可以试试这个。

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]