I want to change the datatypes of only some elements of a list in python

时间:2017-06-12 16:48:43

标签: list type-conversion

I have a list that contains something like this

 [['11.0' 'Switchgear and Protection' '' '' '' '25569.0' '26299.0']
 ['12.0' 'Synchronising' '' '' '' '25569.0' '26299.0']
 ['13.0' 'Transformers and Protection' '' '' '' '25569.0' '26299.0']
 ['14.0' 'Turbine' '' '' 'Name' '25569.0' '26299.0']
 ['15.0' 'Cooling Water' '' '' '' '25569.0' '26299.0']
 ['16.0' 'Water Cycle' '' '' '' '25569.0' '26299.0']]

I want to change the first and last two coloumns to type int but have been unsuccessful. (learning a new language is not all it is cracked up to be...)

Thanks Paul

1 个答案:

答案 0 :(得分:0)

这是一种可行的方法:

listoflists=[ ['11.0', 'Switchgear and Protection', '', '', '', '25569.0', '26299.0'],
              ['12.0', 'Synchronising', '', '', '', '25569.0', '26299.0'],
              ['13.0', 'Transformers and Protection', '', '', '', '25569.0', '26299.0'],
              ['14.0', 'Turbine', '', '', 'Name', '25569.0', '26299.0'],
              ['15.0', 'Cooling Water', '', '', '', '25569.0', '26299.0'],
              ['16.0', 'Water Cycle', '', '', '', '25569.0', '26299.0'] ]
for i in xrange(len(listoflists)):
    for j in xrange(len(listoflists[i])):
        try:
            listoflists[i][j] = int(float(listoflists[i][j]))
        except:
            pass

我不确定是否有更简单的方法。