擅长:python、mysql、java
<p>借用@wim<a href="https://stackoverflow.com/a/49247980/2336654">https://stackoverflow.com/a/49247980/2336654</a></p>
<p>最普遍的解决方案是允许任意嵌套的列表。另外,我们可以关注字符串元素是否相等,而不是包含。在</p>
<pre><code># This import is for Python 3
# for Python 2 use `from collections import Iterable`
from collections.abc import Iterable
def flatten(collection):
for x in collection:
if isinstance(x, Iterable) and not isinstance(x, str):
yield from flatten(x)
else:
yield x
df1[df1.X.map(lambda x: any('hello' == s for s in flatten(x)))]
A B X
1 1 e [hello]
2 3 f [[something], [hello]]
</code></pre>
<p>所以现在如果我们把它复杂化</p>
^{pr2}$
<p>我们的过滤器不抓取<code>hello world</code>,而是抓取非常嵌套的<code>hello</code></p>
<pre><code>df1[df1.X.map(lambda x: any('hello' == s for s in flatten(x)))]
A B X
1 1 e [hello]
2 3 f [[something], [hello]]
4 7 s [[[[[['hello']]]]]]
</code></pre>