gpt4 book ai didi

python - 将字符串转换为元组

转载 作者:IT老高 更新时间:2023-10-28 22:23:24 26 4
gpt4 key购买 nike

我需要编写一个函数,它接受一个字符串 '(1,2,3,4,5),(5,4,3,2,1)' 并返回第一个和最后一个元素的元组列表每个元组的 [(1,5),(5,1)]。我在想:

def f(givenstring):
a=givenstring.split(',')
for i in a[0:-1]:
tuple(int(i[0,-1]))

但我在这里卡住了..

最佳答案

您可以使用 ast.literal_eval() :

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

在你的例子中:

from ast import literal_eval
s = '(1,2,3,4,5),(5,4,3,2,1)'

l = literal_eval(s)
print l
# ((1, 2, 3, 4, 5), (5, 4, 3, 2, 1))

print [(x[0], x[-1]) for x in l]
# [(1, 5), (5, 1)]

关于python - 将字符串转换为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8494514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com