简体   繁体   English

将嵌套元组列表转换为元组列表

[英]Convert list of nested tuples to list of tuples

I have a list of strings but some of the strings have one or two tuples in them such as我有一个字符串列表,但其中一些字符串中有一个或两个元组,例如

["('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00')", "('829.37', '381.62', '1022.00', '491.63')"]

I need this to be a list of single tuples instead like我需要这是一个单元组列表,而不是像

[('829.37', '381.62', '1022.00', '491.63'), ('123.00', '37.00', '813.74', '139.00'), ('753.00', '97.00', '863.74', '179.00')]

Problem is that I have not been able to separate the following because it is enclosed in the same quote.问题是我无法将以下内容分开,因为它包含在同一个引号中。

"('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00')" into ('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00')

I tried list(map(ast.literal_eval, lst)) but that does work as from a previous post that someone marked duplicate.我试过list(map(ast.literal_eval, lst))但这确实像以前有人标记为重复的帖子一样。

This seems like an issue with the data pipeline upstream.这似乎是上游数据管道的问题。 Whatever is generating this should probably be where it should be fixed.无论产生什么,这都应该是应该修复的地方。

That said, the following should do what you need:也就是说,以下应该做你需要的:

import ast

entries = [
    "('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00')",
    "('829.37', '381.62', '1022.00', '491.63')"
]

output_entries = list()
for entry in entries:
    obj = ast.literal_eval(entry)
    if obj and isinstance(obj[0], tuple):
        output_entries.extend(obj)
    else:
        output_entries.append(obj)
print(output_entries)

This prints:这打印:

[('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00'), ('829.37', '381.62', '1022.00', '491.63')]

Or, do what @Samwise suggests in the comments, but with ast.literal_eval(...) :或者,按照@Samwise 在评论中的建议进行操作,但使用ast.literal_eval(...)

import ast
output_entries = list(ast.literal_eval(','.join(entries)))

Because using ast.literal_eval(...) is safer: https://stackoverflow.com/a/15197698/604048因为使用ast.literal_eval(...)更安全: https : ast.literal_eval(...)

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.如果输入不是有效的 Python 数据类型,则ast.literal_eval会引发异常,因此如果不是,则不会执行代码。

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

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