簡體   English   中英

如何從字符串列表中刪除引號和內括號

[英]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']

您可以在列表理解中傳遞的字符串上使用evalstrip函數的組合:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM