1

我试图找到这个答案,但只能在我难以拼凑的部分中找到它。

假设我有:

aList = [["Monday", "2.03","4.03"],["Tuesday","4.03","5.03"],["Wednesday","3.2","4.3"]]

我想遍历这个嵌套列表并将编号的字符串值更改为浮点数。

4

2 回答 2

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]]
于 2013-02-13T08:23:47.530 回答
1
for item in aList:
    item[1] = float(item[1])
    item[2] = float(item[2])
于 2013-02-13T08:24:06.677 回答