相关:Remove all the elements that occur in one list from another
我有listA [1, 1, 3, 5, 5, 5, 7]和listB [1, 2, 5, 5, 7],我想从listA中减去项目的出现。结果应该是一个新的列表:[1, 3, 5]注释:
1在listA中出现了2次,在listB中出现过一次,现在显示为2-1=1次。2没有出现在listA中,所以什么都没有发生3保持1次出现,因为它不在listB中5在listA中发生3次,在listB中发生2次,所以现在发生3-2次=1次。7发生在listA中一次,在listB中一次,所以现在它将出现1-1=0次。这有道理吗?
发布于 2016-07-23 17:09:55
以下是Python新手的非列表理解版本
listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]
for i in listB:
if i in listA:
listA.remove(i)
print listA发布于 2016-07-23 17:04:14
在这种情况下,应该始终使用列表理解:
listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]
newList = [i for i in listA if i not in listB or listB.remove(i)]
print (newList)以下是研究结果:
[1, 3, 5]
https://stackoverflow.com/questions/38544296
复制相似问题