2024-04-26 22:28:38 发布
网友
我有一个如下列表:
["['mnmd']", "['iphones']", "['aapl']", "['apple']", "['gme']", "['aapl']", "['msft']", "['🇸']", "['yolo']"]
有没有简单的pythonic方法来删除外部引号和内部括号
您可以使用ast.literal_eval:
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']
您可以使用
ast.literal_eval
:或
您可以对在list comprehension中传递的字符串使用^{} 和^{} 函数的组合:
相关问题 更多 >
编程相关推荐