[英]Subtract 2 lists by duplicate elements in python
您好,我想知道如何在 python 中通过重复元素而不是值来减去 2 个列表。
ListA = [G, A, H, I, J, B]
ListB = [A, B, C]
ListC = [G, H, I, J]
所以我们减去 ListB 的值,如果它们在 ListA 中被发现是重复的,ListC 将返回 ListA 中的非重复值。
用数学写成:
列表 C = 列表 A - (列表 A ∩ 列表 B)
(我不想去掉ListA中的重复,只去掉ListA和ListB的交集,如上面公式所述,所以这道题不是重复的questions/48242432
您可以进行列表理解。
[x for x in listA if x not in listB]
尝试这个
>>> def li(li1,li2):
li3=li1
for i in li2:
if i in li1:
li3.remove(i)
return(li3)
>>> li(["G","A","H","I","J","B"],["A","B","C"])
['G', 'H', 'I', 'J']
在Python中使用sets库。
from sets import Set
setA = Set(['G', 'A', 'H', 'I', 'J', 'B'])
setB = Set(['A', 'B', 'C'])
# get difference between setA and intersection of setA and setB
setC = setA - (setA & setB)
关于集合的最酷的事情是它们的运行速度往往比列表理解速度要快。 例如,该操作将趋向于在运行O(len(setA)) + O(min(len(setA), len(setB))) = O(len(setA))
而列表解析将在运行O(len(setA) * len(setB))
获得相同的结果。 当然,这些是普通情况,不是最坏情况。 最坏的情况是,它们将是相同的。 无论哪种方式,都应该使用最适合您的操作的对象,对吗?
有关更多信息,请参见Python文档 。
这就是你想要的吗?
L1 = ['A', 'G', 'H', 'I', 'J', 'B']
L2 = ['A', 'B', 'C']
for i in L1:
if i not in L2:
print(i)
在使用数学集合符号的基础上,为什么不使用集合?
ListA = [G,A,H,I,J,B]
ListB = [A,B,C]
SetC = set(ListA) - set(ListB)
但是随后您需要进行设置,并且必须返回列表...而且顺序可能会更改,并且列表中两次出现的任何字符都只会出现一次
https://docs.python.org/3/tutorial/datastructures.html#sets
>>> a = set('abracadabra') # sets have only unique elements and are unordered >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'}
list1 = ['string1','string2','string3']
list2 = ['string1','string2','string3','pussywagon']
newList = list(set(list2)-set(list1))
# output
print(newList)
# type
print(type(newList))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.