![](/img/trans.png)
[英]How to remove brackets and quotations when exporting a list of tuples to TSV
[英]How to remove quotations and then inner brackets from a list of strings
我有一個看起來像這樣的列表:
["['mnmd']",
"['iphones']",
"['aapl']",
"['apple']",
"['gme']",
"['aapl']",
"['msft']",
"['🇸']",
"['yolo']"]
有沒有簡單的pythonic方法來刪除外引號,然后是內括號?
您也許可以使用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']
您可以在列表理解中傳遞的字符串上使用eval
和strip
函數的組合:
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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.