將Python中列表的字串表示形式轉換為列表
由於Python處理各種資料型別,我們會遇到列表以字串形式出現的情況。在本文中,我們將瞭解如何將字串轉換為列表。
使用strip和split
我們首先應用strip方法去除方括號,然後應用split函式。使用逗號作為引數的split函式從字串建立列表。
示例
stringA = "[Mon, 2, Tue, 5,]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = stringA.strip('][').split(', ')
# Result and its type
print("final list", res)
print(type(res))輸出
執行以上程式碼,得到以下結果:
Given string [Mon, 2, Tue, 5,] final list ['Mon', '2', 'Tue', '5,']
使用json.loads
json模組可以直接將字串轉換為列表。我們只需傳入字串作為引數即可應用該函式。這裡我們只能考慮數值元素。
示例
import json
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = json.loads(stringA)
# Result and its type
print("final list", res)
print(type(res))輸出
執行以上程式碼,得到以下結果:
Given string [21,42, 15] final list [21, 42, 15]
使用ast.literal_eval
ast模組提供literal_eval函式,可以直接將字串轉換為列表。我們只需將字串作為引數傳遞給literal_eval方法即可。這裡我們只能考慮數值元素。
示例
import ast
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = ast.literal_eval(stringA)
# Result and its type
print("final list", res)
print(type(res))輸出
執行以上程式碼,得到以下結果:
Given string [21,42, 15] final list [21, 42, 15]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP