【问题标题】:Deriving a new list of lists from two other lists, where the elements from L1 are appended if they're not in L2从其他两个列表派生一个新列表列表,如果 L1 中的元素不在 L2 中,则将其追加
【发布时间】:2018-12-12 22:16:52
【问题描述】:

所以我一直在为即将到来的考试而学习,在练习时我发现了这个脚本;这应该返回一个新的列表列表,其中包含来自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 会很好,因为我不想提交这个,而是在测试前了解基础知识。

【问题讨论】:

  • 这里有三种不同的方式,使用越来越先进的结构:gist.github.com/juanarrivillaga/…
  • @juanpa.arrivillaga 好人,我用的是第一种方法;虽然我没有使用zip,但工作方式相同。你会说我可以避免在该脚本中使用break 吗?
  • 不确定您对zip 的意思,我也没有使用它。但是,是的,你可以省略休息,但它不会短路。本质上,带有布尔标志的循环重新实现了any
  • @juanpa.arrivillaga 哦,对不起,我的意思是set,好吧
  • 嗯,你真的应该使用一套。您可以直接使用L2,但列表成员资格测试很昂贵。如果您期望 L2 很大,那么绝对值得转换

标签: python python-3.x


【解决方案1】:
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() 构造函数..

【讨论】:

  • 这实在是太低效了:len(list(set(sub_list).intersection(l2))) == 0: 并且不需要len(list(...)) == 0set 对象已经有一个长度,无论如何,你可以只使用if not set(sub_list).intersection(l2)
【解决方案2】:
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]

【讨论】:

    【解决方案3】:

    查看会员资格,可以使用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])]
    

    【讨论】:

    • xy 未声明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多