Python:获取没有其他lis中的项的新列表

2024-05-17 17:40:00 发布

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

我想用mainlist中的元素创建一个新列表,其他列表中的元素除外

如何在Python2.7中执行以下操作。有没有什么快速的内置函数来实现?你知道吗

  Input (Mainlist) :[['P', ['not', 'R']], [['not', 'Q'], ['not', 'R'], 'P']]
  Input (Otherlist) : ['P', ['not', 'R']] 

  Output (NewlistIwant) : [['not', 'Q']]

即主列表中的所有内容,除了两项“p”和[“not”,“R”]


Tags: 函数元素内容列表inputoutputnot内置
3条回答

您可以使用列表理解:

[element for element in MainList if element not in OtherList]

如果我理解的没错,你有一个列表列表,每个列表都有一些字符串和列表的组合。你想去掉内部列表中其他列表中的所有内容。你知道吗

下面的代码适用于我。你知道吗

>>> mainlist = [['P', ['not', 'R']], [['not', 'Q'], ['not', 'R'], 'P']]
>>> otherlist = ['P', ['not', 'R']]
>>> def filter_list():
        newlist = []
        for list_ in mainlist:
            for item in list_:
                if item not in otherlist:
                    newlist.append(item)
        return newlist

>>> filter_list()
[['not', 'Q']]

请注意,这是不安全的-如果你变异旧的名单你会弄乱你的新名单。你知道吗

>>> a = filter_list()
>>> mainlist[1][0][1] = 'L'
>>> a
[['not', 'L']]

不清楚你是否想要这种行为。你知道吗

使用方法如下:

def getRemainingLiterals(prop):

    remainingList = []

    for item in prop:
        if isinstance(item, list): #list                    
            for literal1 in item:
                if literal1 not in deletedList:
                    remainingList.append(literal1)

        else:  #str
            if item not in deletedList :
                remainingList.append(item) 

    return remainingList

相关问题 更多 >