如何从字符串列表中删除引号和内括号

2024-04-26 22:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下列表:

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

有没有简单的pythonic方法来删除外部引号和内部括号


2条回答

您可以使用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']

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

您可以对在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']

相关问题 更多 >