我试图找到这个答案,但只能在我难以拼凑的部分中找到它。
假设我有:
aList = [["Monday", "2.03","4.03"],["Tuesday","4.03","5.03"],["Wednesday","3.2","4.3"]]
我想遍历这个嵌套列表并将编号的字符串值更改为浮点数。
我试图找到这个答案,但只能在我难以拼凑的部分中找到它。
假设我有:
aList = [["Monday", "2.03","4.03"],["Tuesday","4.03","5.03"],["Wednesday","3.2","4.3"]]
我想遍历这个嵌套列表并将编号的字符串值更改为浮点数。
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]]
for item in aList:
item[1] = float(item[1])
item[2] = float(item[2])