-2

我想看看是否有更好的方法来执行以下操作:

我有一个字符串列表,实际上可能是浮点数、字母和其他字符,如“-”和“*”:

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

你们看什么?

4

3 回答 3

1

如果列表中的值可以用 分隔x[0].isdigit(),则可以使用列表推导。这意味着您的列表中不会有''or'2E''-3'or '.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', '*']
>>> 
于 2013-07-24T08:55:06.750 回答
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
于 2013-07-24T08:47:05.020 回答
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]
于 2013-07-24T08:58:59.543 回答