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

时间:2021-04-29 11:58:06

标签: python

我有一个看起来像这样的列表:

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以对传入 eval 的字符串使用 striplist 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']
相关问题