[英]list of tuple of string to return in list in python
編寫一個 function ,它采用給定格式的字符串返回下面給定格式的列表
input: "[(694, 104), (153, 236), (201, 106), (601, 427)]"
o/p:
(694, 104)
(153, 236)
(201, 106)
(601, 427)
我已經編寫了以下代碼,但沒有得到正確的 output:
def convertor(string):
result = (string.split(" "))[0]
return result
string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"
print(convertor(string1.replace("[","").replace("]","")))
您可以使用ast.literal_eval
import ast
arr = ast.literal_eval("[(694, 104), (153, 236), (201, 106), (601, 427)]")
for ele in arr:
print(ele)
Output
(694, 104)
(153, 236)
(201, 106)
(601, 427)
如何使用ast.literal_eval
:
import ast
def convertor(string):
return ast.literal_eval(string)
string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"
print(convertor(string1))
實現這一目標的最簡單方法是使用eval
(您不需要導入任何內容):
eval(string1)
# -> [(694, 104), (153, 236), (201, 106), (601, 427)]
但是,如果你真的只想使用str
和list
方法:
def convertor(string):
result = string.strip('[)]').split('), ')
result = [s+')' for s in result]
return result
string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"
print(convertor(string1))
# -> ['(694, 104)', '(153, 236)', '(201, 106)', '(601, 427)']
要重現准確的 output:
for item in convertor(string1):
print(item)
(694, 104)
(153, 236)
(201, 106)
(601, 427)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.