简体   繁体   中英

how convert a string to a list?

I have a problem. I wrote my result (which was a nested list) in a csv file but I don't have it as a list now. It's a string and I can't turn it into a list.

"[['ariba',        index  ...                                       OriginalText\n100      100  ...  \\n\\n\\n\\n\\n\\nintroduction\\nas an ibm applicatio...\n126      126  ...  \\n\\n\\n\\n\\n\\n\\n\\n\\n\\njob description\\njob descr...\n166      166  ...  ust is looking for a sap s/4hana, ecc, sap scm...\n207      207  ...  job title :- sap mdg architect\\nlocation :- ba...\n307      307  ...  \\n\\nintroduction\\n\\n\\nas a package consultant ...\n...      ...  ...                                                ...\n50375  50375  ...  accenture is a leading global professional ser...\n50522  50522  ...  \\n\\nbh: 3514573\\n\\n\\n***** must be able to wor...\n50559  50559  ...  job description\\nfor a \\npromising career deve...\n50616  50616  ...  \\n\\n\\n\\n\\n\\n\\n\\n\\n\\njob description\\na leading...\n50830  50830  ...  stefanini is looking for a enterprise architec...\n\n[963 rows x 4 columns], 0.03690168409406433], ['excel dashboards',        index  ...                                       OriginalText\n67        67  ...  description\\nabout lumen\\nlumen is guided by o...\n167      167  ...  the panum group is looking for an energetic en...\n188      188  ...  at pitcher, we thrive on innovation\\n\\n\\n\\npit...\n240      240  ...  company description\\nas one of the largest ind...\n252      252  ...  founded in hong kong since 2003 to serve busin...\n...      ...  ...                                                ...\n50518  50518  ...  deloitte is the largest private professional s...\n50667  50667  ...  the \\nenterprise architect (ea)\\n works with s...\n50780  50780  ...  \\n\\nat basin electric, our employees are the h...\n50948  50948  ...  \\n\\n\\n\\n\\n\\n\\n\\n\\n\\njob summary\\nthe sr. solut...\n50972  50972  ...  \\n\\n\\n\\n\\n\\n\\n\\n\\n        morgan, lewis & bock...\n\n[769 rows x 4 columns], 0.038849737036863105]]"

The above is just 2 elements of my list. As you can see, the second elements of each sublist is pretty messy, and I can't find any thing to split it as a list. The above example has the following structure:

"[['A','B'],['C','D']]"

as I mentioned B and D are complicated? Is there any way to perform this conversion?

You can use ast.literal_eval() to transform the string to a Python list if you can spell out all of the strings that will be in the list in advance. Don't use eval() like the comment suggests: it's dangerous .

import ast
ast.literal_eval("[['A','B'],['C','D']]")

This outputs:

[['A', 'B'], ['C', 'D']]

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