我试图找到这个答案,但只能找到我难以拼凑的部分。
假设我有:
aList = [["Monday", "2.03","4.03"],["Tuesday","4.03","5.03"],["Wednesday","3.2","4.3"]]
我想迭代这个嵌套列表并将编号的字符串值更改为浮点数。
答案 0 :(得分:8)
aList = [["Monday", "2.03","4.03"],
["Tuesday","4.03","5.03"],
["Wednesday","3.2","4.3"]]
def helper(s):
try: return float(s)
except ValueError: return s
aList[:] = [[helper(item) for item in subl] for subl in aList]
print aList
出:
[['Monday', 2.03, 4.03], ['Tuesday', 4.03, 5.03], ['Wednesday', 3.2, 4.3]]
答案 1 :(得分:1)
for item in aList:
item[1] = float(item[1])
item[2] = float(item[2])