<p>因此,我一直在为即将到来的测试而学习,在练习时我发现了这个脚本;它应该返回一个新的列表列表,其中包含来自<code>L1</code>的列表,而不包含来自<code>L2</code>的任何字符串:</p>
<p>我所做的是将<code>L2</code>中的每个元素与<code>L1</code>中的元素进行比较,并将它们添加到<code>listas</code>中,而没有任何重复。我陷入困境的部分是在循环运行完成之后,我得到了一个列表列表,但没有任何实际的比较。我尝试过使用第二个列表,但如果<code>len(L2) > 2</code>它不起作用,也<code>.remove()</code>但有时要删除的元素还不在列表中,我会遇到一些错误。你知道吗</p>
<pre><code>from typing import List
def non_intersecting(L1: List[List[str]], L2: List[str]) -> List[List[str]]:
"""Return a new list that contains the original lists inside L1 that do not
contain any of the string in L2
>>> non_intersecting([['e', 'h', 'c', 'w'], ['p', 'j'], ['w', 's', 'u']], ['k', 'w'])
[['p', 'j']]
"""
listas = []
if len(L2) == 0:
return L1
elif len(L2) > 0:
for index in range(len(L2)):
for lists in L1:
if lists not in listas:
if L2[index] not in lists:
listas.append(lists)
return listas
</code></pre>
<p>有什么帮助吗?如果不使用任何模块或<code>zip</code>,<code>lambdas</code>,那就太好了,因为我不想提交这个,而是想在测试前了解基本知识。你知道吗</p>
<pre><code>def non_intersecting(L1, L2):
s2 = set(L2)
lists_sets = ((l, set(l)) for l in L1)
return [l for l, s in lists_sets if not s & s2]
</code></pre>