简体   繁体   中英

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.

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(...) :

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 raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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