在一個 csv 檔案中,我保存了一個 list(tuple(int, int)) 但是在讀取該行時我得到一個字串,但是如何將這個 "[(56, 365), (62, 801)]" 轉換為 [(56 , 365), (62, 801)]
uj5u.com熱心網友回復:
import ast
new_list = ast.literal_eval(your_list)
這應該可以解決您的問題!
uj5u.com熱心網友回復:
在不使用庫的情況下解決此問題的另一種方法是操縱字串以提供您想要的內容。這是我在其中輸入字串的一些代碼,將其決議為整數并為輸出所需的格式構建了一個新陣列。可能有一種更簡單的方法來操縱字串,但這是一個有效的第一槍。
string_array = "[(56, 365), (62, 801)]"
no_spaces = string_array.replace(" ","")
without_Lbrackets = no_spaces.replace("[","")
without_brackets = without_Lbrackets.replace("]","")
without_Lparantheses = without_brackets.replace("(","")
without_parantheses = without_Lparantheses.replace(")","")
strarray = without_parantheses.split(",")
intarray = [(int(strarray[0]),int(strarray[1])),(int(strarray[2]),int(strarray[3]))]
print(intarray)
uj5u.com熱心網友回復:
一個簡單但不是很安全的方法是使用eval(line)要line決議的字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492220.html
標籤:Python python-3.x 列表
