我有一个看起来像这样的列表:
["['mnmd']",
"['iphones']",
"['aapl']",
"['apple']",
"['gme']",
"['aapl']",
"['msft']",
"['?']",
"['yolo']"]
有没有简单的pythonic方法来删除外部引号然后删除内部括号?
答案 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
的字符串使用 strip
和 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']