我有一個問題無法解決,我有一個data包含多個串列的動態串列(從網路請求資料),每個串列都包含字串、整數等,但我需要一個包含特定文本的串列StreamCache。并且只有一個串列data包含字串StreamCache,我將其存盤在一個新串列中。幾乎所有時候我的代碼都能完美運行,但是當它找到一個帶有類似StreamCache@abnsdj12or的字串的串列時StreamCache*mljsgfn525,這基本上是我需要的串列,我的代碼不起作用,只是因為StreamCache與 or 不完全匹配StreamCache@kahsgsgh5,我嘗試了 list理解,正則運算式,但沒有任何作用。有人能幫我嗎?這些是我的解決方案:
# Works only if 'StreamCache' matchs exactly with the iterable
temp1 = [i for i in data if 'StreamCache' in i]
################ Solution 2 that doesn't work at all
search = 'StreamCache'
for element in data:
if isinstance(element, list):
new = [i for i in element]
z = re.compile('|'.join(re.escape(k) for k in new))
result = re.findall(z, search)
希望你能幫我解決這個問題。
uj5u.com熱心網友回復:
您需要檢查是否StreamCache是串列中任何字串的一部分,您可以這樣做:
[l for l in data if any('StreamCache' in s for s in l)]
如果StreamCache總是出現在字串的開頭,這會更有效:
[l for l in data if any(s.startswith('StreamCache') for s in l)]
uj5u.com熱心網友回復:
您嘗試的第二種方法僅回傳[StreamCache],因為您搜索的內容僅是StreamCache并且正則運算式物件是<element 1>|<element 2>|....,您的意思是在下面的示例中找到StreamCache.*字串中的字串嗎?
a|abc|StreamCache*mljsgfn777|123|StreamCache|aweafwfa|asfwqwdq|StreamCache@abnsdj12|somestring|StreamCache*mljsgfn525
如果是這樣,我認為你錯誤地得到了引數 reverse,正則運算式物件是第一個引數,搜索內容是第二個引數。下面是一個似乎為我提供預期結果的示例
search = 'a|abc|StreamCache*mljsgfn777|123|StreamCache|aweafwfa|asfwqwdq|StreamCache@abnsdj12|somestring|StreamCache*mljsgfn525' # search content
z = re.compile('StreamCache[^|]*|') # regex object
search_result = list(filter(lambda x: x, re.findall(z, search))) # use filter to remove empty strings
# search_result here would contain ['StreamCache*mljsgfn777', 'StreamCache', 'StreamCache@abnsdj12', 'StreamCache*mljsgfn525']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477414.html
標籤:Python python-3.x 列表 蟒蛇重新
