[英]How to change a string list to a list of integers?
我有一個列表,它結合了來自兩個來源的輸入,最終看起來像下面給出的“pde_fin”。 我需要提取列表中元素的 integer 值以進行進一步處理。 但是,第二組數字似乎給出了一個錯誤(“invalid literal for int() with base 10:”'1118'")。
pde_fin =['2174', '2053', '2080', '2160', '2065', "'1118'", "'1098'", "'2052'", "'2160'", "'2078'", "'2161'", "'2134'", "'2091'", "'2089'", "'2105'", "'2109'", "'2077'", "'2057'"]
for i in pde_fin:
print(int(i))
最簡單的解決方法是去掉單引號:
for i in pde_fin:
print(int(i.strip("'")))
使用以下代碼更正您的值:
pde_fin =['2174', '2053', '2080', '2160', '2065', "'1118'", "'1098'", "'2052'", "'2160'", "'2078'", "'2161'", "'2134'", "'2091'", "'2089'", "'2105'", "'2109'", "'2077'", "'2057'"]
for i in pde_fin:
print(int(i.replace("'",'')))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.