比较python中的'list'
我有多张名单。我需要找到一种方法来生成每个列表中唯一项的列表,并与所有列表进行比较。有什么简单或直接的方法可以做到这一点。我知道这些列表基本上可以用作比较python中的'list',python,list,unique,set,Python,List,Unique,Set,我有多张名单。我需要找到一种方法来生成每个列表中唯一项的列表,并与所有列表进行比较。有什么简单或直接的方法可以做到这一点。我知道这些列表基本上可以用作sets 使用集合类和其中定义的集合操作: >>> l1 = [1,2,3,4,5,5] >>> l2 = [3,4,4,6,7] >>> set(l1) ^ set(l2) # symmetric difference set([1, 2, 5, 6, 7]) 编辑:啊,误读了你的问题
set
s 使用集合类和其中定义的集合操作:
>>> l1 = [1,2,3,4,5,5]
>>> l2 = [3,4,4,6,7]
>>> set(l1) ^ set(l2) # symmetric difference
set([1, 2, 5, 6, 7])
编辑:啊,误读了你的问题。如果您的意思是,“在l1
中不在任何l2、l3、…、ln
中的唯一元素,那么:
l1set = set(l1)
for L in list_of_lists: # list_of_lists = [l2, l3, ..., ln]
l1set = l1set - set(L)
所以
为了提高效率,您可以一次将所有列表转换为集合。import itertools
import itertools
# Test set
lists = []
lists.append([1,2,3,4,5,5])
lists.append([3,4,4,6,7])
lists.append([7,])
lists.append([8,9])
lists.append([10,10])
# Join all the lists removing the duplicates in each list
join_lists = []
for list_ in lists:
join_lists.extend(set(list_))
# First, sort
join_lists.sort()
# Then, list only the groups with one element
print [ key for key, grp in itertools.groupby(join_lists) if len(list(grp)) < 2 ]
#>>> [1, 2, 6, 8, 9]
###
#测试集
列表=[]
lists.append([1,2,3,4,5,5])
列表。追加([3,4,4,6,7])
列表。追加([7,])
lists.append([8,9])
列表。追加([10,10])
#加入所有列表删除每个列表中的重复项
加入列表=[]
对于列表中的列表:
加入列表。扩展(集合(列表)
#首先,分类
join_list.sort()
#然后,仅列出具有一个元素的组
如果len(list(grp))<2,则在itertools.groupby(join_list)中打印[key for key,grp]
#>>> [1, 2, 6, 8, 9]
###
结果是:
>>> set([8, 9])
使用
set()
,您还需要什么?因此,对于每个列表,您希望找到不在任何其他列表中的元素?除了“set()”之外,还有更多的逻辑“找出每个列表的独特之处。我想他/她指的是‘对于每个列表,生成该列表中出现的项目,但不生成其他项目’。@phooji是正确的,很抱歉我之前不清楚。新奇。但是使用set API更具python风格,你不认为吗?@santa:除了这样可以避免编写(n-1)的所有可能组合之外设置。如果一个组包含一个值的多个实例(即4),则即使没有其他组包含该值,也将取消其资格。对于n个输入列表,必须重复此过程n次(l1的项目不在l2、l3、l4中,l2的项目不在l1、l3、l4中,l3的项目不在l1、l2、l4中,l4的项目不在l1、l2、l3中)。
for l in lists:
s = set(l)
for o in lists:
if o != l:
s -= set(o)
# At this point, s holds the items unique to l
import itertools
# Test set
lists = []
lists.append([1,2,3,4,5,5])
lists.append([3,4,4,6,7])
lists.append([7,])
lists.append([8,9])
lists.append([10,10])
# Join all the lists removing the duplicates in each list
join_lists = []
for list_ in lists:
join_lists.extend(set(list_))
# First, sort
join_lists.sort()
# Then, list only the groups with one element
print [ key for key, grp in itertools.groupby(join_lists) if len(list(grp)) < 2 ]
#>>> [1, 2, 6, 8, 9]
###
l1 = [4, 6, 3, 7]
l2 = [5, 5, 3, 1]
l3 = [2, 5, 4, 3]
l4 = [9, 8, 7, 6]
# first find the union of the "other" lists
l_union = reduce(set.union, (map(set, (l1, l2, l3))))
# then subtract the union from the remaining list
uniques = set(l4) - l_union
print uniques
>>> set([8, 9])