a=[[1,2,'g'],[2,4,'f']]
b=[[2,4,'f'],[1,2,'f']]
a和b的并集是
c=[[1,2,'g'],[2,4,'f'],[1,2,'f']]
无法使用set().union
,怎么破?只能自己实现遍历么?
大家讲道理2017-04-17 17:28:55
You can use the following code to achieve it:
a=[[1,2,'g'],[2,4,'f']]
b=[[2,4,'f'],[1,2,'f']]
tmp = a + b
c = [ (tmp[i]) for i in range(0, len(tmp)) if tmp[i] not in tmp[:i] ]
Check results:
print c
[[1, 2, 'g'], [2, 4, 'f'], [1, 2, 'f']]
天蓬老师2017-04-17 17:28:55
It can be like this:
a=[[1,2,'g'],[2,4,'f']]
b=[[2,4,'f'],[1,2,'f']]
c=[list(i) for i in set(tuple(j) for j in a+b)]
Check results:
print c
[[2, 4, 'f'], [1, 2, 'f'], [1, 2, 'g']]
ringa_lee2017-04-17 17:28:55
It is definitely not possible to use set operations directly, because the elements in the list are still lists, which are mutable objects, and the objects of set operations must be immutable objects, so if you want to repeat it, the simpler method is The reply above is converted into an immutable object tuple, so that the set can be deduplicated. As follows, it is actually traversal.
map(list,set(map(tuple, a + b)))