简体   繁体   中英

How to remove quotations and then inner brackets from a list of strings

I have a list that looks like this:

["['mnmd']",
 "['iphones']",
 "['aapl']",
 "['apple']",
 "['gme']",
 "['aapl']",
 "['msft']",
 "['🇸']",
 "['yolo']"] 

Is there any simple pythonic way to remove the outer quotations and then the inner brackets?

You may be able to use ast.literal_eval :

>>> x = ["['mnmd']",
...  "['iphones']",
...  "['aapl']",
...  "['apple']",
...  "['gme']",
...  "['aapl']",
...  "['msft']",
...  "['🇸']",
...  "['yolo']"]
>>> x
["['mnmd']", "['iphones']", "['aapl']", "['apple']", "['gme']", "['aapl']", "['msft']", "['🇸']", "['yolo']"]
>>> [item for s in x for item in ast.literal_eval(s)]
['mnmd', 'iphones', 'aapl', 'apple', 'gme', 'aapl', 'msft', '🇸', 'yolo']

or

>>> from itertools import chain
>>> list(chain.from_iterable(map(ast.literal_eval, x)))
['mnmd', 'iphones', 'aapl', 'apple', 'gme', 'aapl', 'msft', '🇸', 'yolo']

You can use a combinatio of eval andstrip functions on string passed in a list comprehension :

sample_list = ["['mnmd']",
               "['iphones']",
               "['aapl']",
               "['apple']",
               "['gme']",
               "['aapl']",
               "['msft']",
               "['🇸']",
               "['yolo']"]

outlist = [eval(entry.strip("[]")) for entry in sample_list]
>>> outlist
['mnmd', 'iphones', 'aapl', 'apple', 'gme', 'aapl', 'msft', '🇸', 'yolo']

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