Python:确定未排序的列表是否包含在“列表列表”中,而不管元素的顺序如何

2024-04-19 15:51:01 发布

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

我有一个类似的问题:Determine if 2 lists have the same elements, regardless of order?

确定未排序的列表list1是否包含在“列表列表”myListOfLists中的最佳/最快速方法是什么,而不管list1中元素的顺序如何?我的尝试包含在我多次调用的函数doSomething(...)中:

def doSomething(myListOfLists, otherInputs):

    list1 = []
    ...  # do something here with `otherInputs' 
    ...  # which gives `list1' some values

    # now only append `list1' to `myListOfLists' if it doesn't already exist
    # and if it does exist, remove it

    removeFromList = False
    for myList in myListOfLists:
        if sorted(list1) == sorted(myList):
            removeFromList = True
            break

    if removeFromList:
        myListOfLists.remove(list1)
    else:
        myListOfLists.append(list1)

    return myListOfLists

问题是我需要运行函数doSomething(...)大约1.0e5次。随着myListOfLists随着doSomething(...)的每次调用变得越来越大,这就变得非常耗时。你知道吗

编辑:

对任务的一些澄清。让我举一个期望输出的例子:

a = []
doSomething(a, [1,2,3])
>> a = [1,2,3]

因为[1,2,3]不在a中,所以它被附加到a。你知道吗

doSomething(a, [3,4,5])
>> a = [[1,2,3], [3,4,5]]

因为[3,4,5]不在a中,所以它被附加到a。你知道吗

doSomething(a, [1,2,3])
>>[3,4,5]

因为[1,2,3]a中的,所以它被从a中删除。你知道吗

编辑:

所有列表长度相同。你知道吗


Tags: 函数编辑列表ifitremoveexistsorted
3条回答

如果对给定列表排序,然后将其附加到myListOfLists,则可以使用以下方法:

if sorted(list1) in myListOfLists:

使用集合

def doSomething(myDictOfLists, otherInputs):

    list1 = []
    ...  # do something here with `otherInputs' 
    ...  # which gives `list1' some values

    # now only append `list1' to `myListOfLists' if it doesn't already exist
    # and if it does exist, remove it
    list1Set = set(list1)
    if list1Set not in myDictOfLists:
        myDictOfLists[list1Set] = list1

    return myDictOfLists

您可以在此处使用集合:

def doSomething(myListOfLists, otherInputs):
    s = set(otherInputs)           #create set from otherInputs
    for item in myListOfLists: 
        #remove the common items between `s` and current sublist from `s`.
        s -= s.intersection(item) 
        #if `s` is empty, means all items found. Return True
        if not s:                  
            return True
    return not bool(s)
... 
>>> doSomething([[1, 2, 7],[6, 5, 4], [10, 9, 10]], [7, 6, 8])
False
>>> doSomething([[1, 2, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
True

更新1:任何子列表都包含与otherInputs完全相同的项。你知道吗

def doSomething(myListOfLists, otherInputs):
    s = set(otherInputs)
    return any(set(item) == s for item in myListOfLists)
... 
>>> doSomething([[6, 8, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
True
>>> doSomething([[1, 2, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
False

更新2:otherInputs是任何子列表的子集:

def doSomething(myListOfLists, otherInputs):
    s = set(otherInputs)
    return any(s.issubset(item) for item in myListOfLists)
... 
>>> doSomething([[6, 8, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
True
>>> doSomething([[6, 8, 7, 10],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
True
>>> doSomething([[1, 2, 7],[6, 5, 4], [10, 8, 10]], [7, 6, 8])
False

相关问题 更多 >