gpt4 book ai didi

python - 如何在Python中将字符串转换为元组列表

转载 作者:行者123 更新时间:2023-12-01 06:41:02 26 4
gpt4 key购买 nike

我有以下格式的字符串,我发现很难将这些类型的字符串转换为元组 -

text = '[(Apple Fruit, 10.88), (Table Top, 1.09), (Kicks, 1.08), (La Liga, 1.05), (Camp Nou, 1.02), (Football Team, 0.82), (, 0.73), (Hattrick, 0.7), (Free kick, 0.68), (Ballon dOr, 0.6), (, 0.53), (Treble, 0.51), (Vinegar, 0.09), (Ronaldo, 0.07)]'

我想将此字符串转换为元组列表 -

output = [('Apple Fruit', 10.88), ('Table Top', 1.09), ('Kicks', 1.08), ('La Liga', 1.05), ('Camp Nou', 1.02), ('Football Team', 0.82), ('', 0.73), ('Hattrick', 0.7), ('Free kick', 0.68), ('Ballon dOr', 0.6), ('', 0.53), ('Treble', 0.51), ('Vinegar', 0.09), ('Ronaldo', 0.07)]

我不知道该怎么做。有人可以帮我解决这个问题吗?

最佳答案

您可以使用convert函数来分割序列构建元组列表。

text = '[(Apple Fruit, 10.88), (Table Top, 1.09), (Kicks, 1.08), (La Liga, 1.05), (Camp Nou, 1.02), (Football Team, 0.82), (, 0.73), (Hattrick, 0.7), (Free kick, 0.68), (Ballon dOr, 0.6), (, 0.53), (Treble, 0.51), (Vinegar, 0.09), (Ronaldo, 0.07)]'

text = text.replace("[","").replace("]","")

def is_digit(str):
return str.lstrip('-').replace('.', '').isdigit()

def convert(in_str):
result = []
current_tuple = []
for token in in_str.split(", "):
chunk = token.replace("(","").replace(")", "")
if is_digit(chunk):
chunk = float(chunk)
current_tuple.append(chunk)
if ")" in token:
result.append(tuple(current_tuple))
current_tuple = []
return result

输出

[('Apple Fruit', 10.88), ('Table Top', 1.09), ('Kicks', 1.08), ('La Liga', 1.05), ('Camp Nou', 1.02), ('Football Team', 0.82), ('', 0.73), ('Hattrick', 0.7), ('Free kick', 0.68), ('Ballon dOr', 0.6), ('', 0.53), ('Treble', 0.51), ('Vinegar', 0.09), ('Ronaldo', 0.07)]

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

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