将嵌套循环中的字符串转换为float

时间:2013-02-14 23:58:15

标签: python nested

这是我的代码 我只需要将数字的字符串转换为浮点数 我有aList =列表列表

    def convertData(aList):
       for items in aList:
          for x in items:
             try:
               float(x)
             except ValueError:
               pass
       print (aList)

这就是我的清单

   aList = [['Date', 'Assembly', 'Heat-treat', 'Painting', 'Inspection'], ['Monday',    '0.352', '0.92', '0.182', '0.255'], ['Tuesday', '0.438', '0.809', '0.155', '0.225'], ['Wednesday', '0.323', '0.9', '0.169', '0.236'], ['Thursday', '0.383', '0.841', '0.172', '0.238'], ['Friday', '0.355', '0.352', '0.177', '0.227']]

2 个答案:

答案 0 :(得分:0)

def convertData(aList):
   for items in aList:
      for i,j in enumerate(items):
         try:
           items[i] = float(j)
         except ValueError:
           continue
   print (aList)

答案 1 :(得分:0)

def convertData(aList):
   lout = []
   for items in aList:
      itemsout = []
      for x in items:
         try:
           itemsout.append(float(x))
         except ValueError:
           itemsout.append(x)
      lout.append(itemsout)
   return lout