python把列表样式的字符串重新转换为列表
做數(shù)據(jù)分析是,遇到這么個(gè)問(wèn)題,一個(gè)變量原來(lái)是一個(gè)列表,為了存儲(chǔ)方便,或者是讀取過(guò)程中的問(wèn)題,變成了列表樣式的字符串,
如下圖:
這個(gè)看上去是列表,而且也想把它變成列表,問(wèn)題是它是字符串,雙引號(hào)里面的字符串,
我嘗試把它轉(zhuǎn)回列表,首先想道的是正則提取,試了試,感覺(jué)很復(fù)
雜,正則的話,要提取單引號(hào)里面的字符
re.findall(r"\'.+?\'", s184)[1]提取出來(lái)還是有單引號(hào),挺麻煩
?
?
看到有高手用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.
也不太明白什么意思、
看了很多其他關(guān)于eval的,還是不明覺(jué)厲,大概的意思明白,應(yīng)該類似于解包,把一個(gè)對(duì)象里面的值通過(guò)提取,還原出來(lái)。功能還是很強(qiáng)大。以后學(xué)到了再繼續(xù)補(bǔ)充,這里暫時(shí)用著。享受一下python的強(qiáng)大。
?
?
?
總結(jié)
以上是生活随笔為你收集整理的python把列表样式的字符串重新转换为列表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: pandas 判断数据表中的缺失值
- 下一篇: vim快速查找