简体   繁体   中英

Python how to get rid of a nested list

Good evening,

I have a python variable like so

myList = ["['Ben'", " 'Dillon'", " 'Rawr'", " 'Mega'", " 'Tote'", " 'Case']"]

I would like it to look like this instead

myList = ['Ben', 'Dillon', 'Rawr', 'Mega', 'Tote', 'Case']

If I do something like this

','.join(myList)

It gives me what I want but the type is a String

I also would like it to keep the type of List. I have tried using the Join method and split method. And I have been debugging use the type() method. It tells me that the type in the original scenario is a list.

I appreciate any and all help on this.

Join the inner list elements, then call ast.literal_eval() to parse it as a list of strings.

import ast

myList = ast.literal_eval(",".join(myList))

Also can be done by truncating Strings, therefore avoiding the import of ast.

myList[5] = (myList[5])[:-1]
for n in range(0, len(myList)):
    myList[n] = (myList[n])[2:-1]

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