因此,我一直在研究即将到来的测试,在练习时我发现了这个脚本;它应该返回一个新的列表列表,其中包含来自L1
的列表,这些列表不包含来自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
,因为我不希望提交这一点,而是了解我的测试前的基础知识。
发布于 2018-12-13 06:32:31
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()构造函数。
发布于 2018-12-13 06:51:46
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]
发布于 2018-12-13 06:52:04
要检查成员资格,可以使用any()
或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])]
https://stackoverflow.com/questions/53752223
复制相似问题