我有一个问题无法解决,我有一个动态的 list data
(从 web 请求数据)包含多个 lists,每个都包含字符串、整数等,但我需要一个其中包含特定文本 StreamCache
。 data
中只有一个list包含字符串StreamCache
,我将它store放在一个新的list中。几乎所有时候我的代码都能完美运行,但是当它找到一个带有 StreamCache@abnsdj12
或 StreamCache*mljsgfn525
之类的字符串的 list 时,本质上就是我需要的 lists,我的代码不起作用,只是因为 StreamCache
与 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)
希望你能帮我解决这个问题。
回答1
您需要检查 StreamCache
是否是 list 中任何字符串的一部分,您可以这样做:
[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)]
回答2
您尝试的第二种方法仅返回 [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']