简体   繁体   English

要在 python 中的列表中返回的字符串元组列表

[英]list of tuple of string to return in list in python

write a function which takes a string in the format given returns a list in given below format编写一个 function ,它采用给定格式的字符串返回下面给定格式的列表

input:  "[(694, 104), (153, 236), (201, 106), (601, 427)]"
o/p: 
(694, 104)
(153, 236)
(201, 106)
(601, 427)

i have written the below code but not getting proper output:我已经编写了以下代码,但没有得到正确的 output:

def convertor(string):
    result = (string.split("  "))[0]
    return result


string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"

print(convertor(string1.replace("[","").replace("]","")))

You can use ast.literal_eval您可以使用ast.literal_eval

import ast
arr = ast.literal_eval("[(694, 104), (153, 236), (201, 106), (601, 427)]")
for ele in arr:
    print(ele)

Output Output

(694, 104)
(153, 236)
(201, 106)
(601, 427)

How about using ast.literal_eval :如何使用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))

The easiest way to achieve that would be using eval (you don't need to import anything):实现这一目标的最简单方法是使用eval (您不需要导入任何内容):

eval(string1)
# -> [(694, 104), (153, 236), (201, 106), (601, 427)]

But, if you really want to use just str and list methods:但是,如果你真的只想使用strlist方法:

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)']

To reproduce the exact output:要重现准确的 output:

for item in convertor(string1):
    print(item)
(694, 104)
(153, 236)
(201, 106)
(601, 427)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM