算法 - Python二维数组怎么求并集?
PHPz
PHPz 2017-04-17 17:26:55
0
3
513
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,怎么破?只能自己实现遍历么?

PHPz
PHPz

学习是最好的投资!

reply all(3)
大家讲道理

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']]
Peter_Zhu

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']]
左手右手慢动作

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)))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template