更改列表中的型別

定量資料通常作為字串讀入,在處理之前必須將其轉換為數字型別。可以使用 List Comprehensionmap() 函式轉換所有列表項的型別。

# Convert a list of strings to integers.
items = ["1","2","3","4"]
[int(item) for item in items]
# Out: [1, 2, 3, 4]

# Convert a list of strings to float.
items = ["1","2","3","4"]
map(float, items)
# Out:[1.0, 2.0, 3.0, 4.0]