Python 字串列表轉換為列表
有時我們可能會遇到包含字串的資料,但資料流內部的結構是一個 Python 列表。在本文中,我們將學習如何將用字串括起來的列表轉換為實際的 Python 列表,以便進一步進行資料處理。
使用 eval 函式
我們知道 eval 函式會返回作為引數提供的實際結果。因此,我們將給定的字串提供給 eval 函式,並獲取 Python 列表。
示例
stringA = "['Mon', 2,'Tue', 4, 'Wed',3]" # Given string print("Given string : \n",stringA) # Type check print(type(stringA)) # using eval res = eval(stringA) # Result print("The converted list : \n",res) # Type check print(type(res))
輸出
執行上述程式碼將得到以下結果:
Given string : ['Mon', 2,'Tue', 4, 'Wed',3] The converted list : ['Mon', 2, 'Tue', 4, 'Wed', 3]
使用 ast.literal_eval 函式
在這種方法中,我們使用 literal_eval 函式,並將字串作為引數傳遞給它。它會返回 Python 列表。
示例
import ast stringA = "['Mon', 2,'Tue', 4, 'Wed',3]" # Given string print("Given string : \n",stringA) # Type check print(type(stringA)) # using literal_eval res = ast.literal_eval(stringA) # Result print("The converted list : \n",res) # Type check print(type(res))
輸出
執行上述程式碼將得到以下結果:
Given string : ['Mon', 2,'Tue', 4, 'Wed',3] The converted list : ['Mon', 2, 'Tue', 4, 'Wed', 3]
使用 json.loads 函式
loads 函式可以進行類似的轉換,其中對字串進行評估並生成實際的 Python 列表。
示例
import json stringA = '["Mon", 2,"Tue", 4, "Wed",3]' # Given string print("Given string : \n",stringA) # Type check print(type(stringA)) # using loads res = json.loads(stringA) # Result print("The converted list : \n",res) # Type check print(type(res))
輸出
執行上述程式碼將得到以下結果:
Given string : ["Mon", 2,"Tue", 4, "Wed",3] The converted list : ['Mon', 2, 'Tue', 4, 'Wed', 3]
廣告