从另外两个列表中导出一个新的列表列表,如果L1中的元素不在L2中,则附加它们

2024-03-28 16:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我一直在为即将到来的测试而学习,在练习时我发现了这个脚本;它应该返回一个新的列表列表,其中包含来自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

有什么帮助吗?如果不使用任何模块或ziplambdas,那就太好了,因为我不想提交这个,而是想在测试前了解基本知识。你知道吗


Tags: in元素l1列表lenifthatnot
3条回答
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]
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()构造函数。。你知道吗

要检查成员身份,可以使用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])]

相关问题 更多 >