python把列表样式的字符串重新转换为列表
做數據分析是,遇到這么個問題,一個變量原來是一個列表,為了存儲方便,或者是讀取過程中的問題,變成了列表樣式的字符串,
如下圖:
這個看上去是列表,而且也想把它變成列表,問題是它是字符串,雙引號里面的字符串,
我嘗試把它轉回列表,首先想道的是正則提取,試了試,感覺很復
雜,正則的話,要提取單引號里面的字符
re.findall(r"\'.+?\'", s184)[1]提取出來還是有單引號,挺麻煩
?
?
看到有高手用eval
很管用
eval(s184)[1]看一下eval的幫助
def eval(__source: Union[str, bytes, CodeType],
? ? ? ? ?__globals: Optional[Dict[str, Any]] = ...,
? ? ? ? ?__locals: Optional[Mapping[str, Any]] = ...) -> Any
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
也不太明白什么意思、
看了很多其他關于eval的,還是不明覺厲,大概的意思明白,應該類似于解包,把一個對象里面的值通過提取,還原出來。功能還是很強大。以后學到了再繼續補充,這里暫時用著。享受一下python的強大。
?
?
?
總結
以上是生活随笔為你收集整理的python把列表样式的字符串重新转换为列表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pandas 判断数据表中的缺失值
- 下一篇: python 把一个列表分成等长的多个列