我试图找到这个答案,但只能找到我难以拼凑的碎片。
假设我有:
aList = [["星期一", "2.03","4.03"],["星期二","4.03","5.03"],["星期三","3.2","4.3"] ]
我想遍历这个嵌套列表并将编号的字符串值更改为 float 。
请您参考如下方法:
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]]
