我有一個格式為:
s = "[2153. 3330.75]"
我想用ints.
預期輸出:l = [2153, 3330]
type(l)是list
uj5u.com熱心網友回復:
以下代碼可以滿足您的需求。
l = [int(float(x)) for x in s.strip('[]').split()]
浮點轉換是必需的,因為字串包含“。” 不能直接轉換為整數。
uj5u.com熱心網友回復:
該字串看起來像一個 numpy 陣列。fromstring首先,我們使用 numpy方法將字串轉換為浮點 numpy 陣列。int然后使用方法將浮點陣列轉換為陣列astype。最后,將 numpy 陣列轉換為listusingtolist方法:
import numpy as np
s = "[2153. 3330.75]"
values = np.fromstring(s[1:-1], dtype=float, sep=' ').astype(int).tolist()
print(values)
輸出:
[2153, 3330]
參考:
- 關于 numpy fromstring 方法的檔案
- 關于 numpy astype 方法的檔案
- 關于 numpy tolist 方法的檔案
uj5u.com熱心網友回復:
lambda您可以使用函式解決此問題。
num = list(map(lambda x: int(float(x)), s.strip("[]").split()))
在這里,s.strip("[]")洗掉方括號。我們使用lambda函式將 all 轉換float為int.
我們使用int(float(x))代替,int(x)因為否則我們ValueError在轉換“2153”時會得到。到int.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492594.html
