所以我一直在为即将到来的测试学习,在练习时我发现了这个脚本;其应该返回包含来自CCD_ 1的列表的新列表,该列表不包含来自L2
:
我所做的是将L2
中的每个元素与L1
中的元素进行比较,并将它们添加到listas
中,不存在任何重复。我陷入困境的部分是在循环运行结束后,我会得到一个列表列表,但没有任何实际的比较。我试着使用第二个列表,它可以工作,但如果len(L2) > 2
不工作,也可以使用.remove()
,但有时要删除的元素还不在列表中,我会遇到一些错误。
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
有什么帮助吗?如果没有任何模块,也没有zip
、lambdas
,那就太好了,因为我不想提交这个,而是在测试前了解基本知识。
def non_intersecting(l1, l2):
out = []
for sub_list in l1:
if len(list(set(sub_list).intersection(l2))) == 0: #no common strings
out.append(sub_list)
return out
对于这个简单的操作,无需添加List((构造函数。。
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]
对于检查会员资格,您可以使用L1
0或not any()
x=[['e', 'h', 'c', 'w'], ['p', 'j'], ['w', 's', 'u']]
y=['k', 'w']
def non_intersecting(l1, l2):
outlist=[]
for sublist in x:
if not any([elem in sublist for elem in y]):
outlist.append(sublist)
return outlist
non_intersecting(x, y)
[['p', 'j']]
以上内容也可以简化为列表理解
def non_intersecting(l1, l2):
return [i for i in x if not any([j in i for j in y])]