从另一个列表中删除列表

时间:2017-06-21 23:18:49

标签: python python-2.7

我想删除元素,如果它出现在a和b(并非所有出现)

add_action( 'woocommerce_single_product_summary', 'mh_output_stock_status', 21 );

function mh_output_stock_status ( ) {
    global $product;

    echo wc_get_stock_html( $product );

}

预期输出

a = [[2.0, 3.0], [1.0, 2.0] , [2.0, 3.0]]
b = [[1.0, 4.0], [2.0, 3.0] , [3.0, 4.0]]

如果一个点在a中出现两次,在b中出现两次,那么输出应该包含两次点

c = [[1.0, 2.0], [2.0, 3.0], [1.0, 4.0], [3.0, 4.0]]

预期输出

a = [[2.0, 3.0], [1.0, 2.0] , [2.0, 3.0]]
b = [[1.0, 4.0], [2.0, 3.0] , [3.0, 4.0], [2.0, 3.0]]

我试过了

c = [[1.0, 2.0], [2.0, 3.0], [1.0, 4.0], [3.0, 4.0], [2.0, 3.0]]

但这会考虑a或b本身的元素。

编辑:澄清的第二个例子

3 个答案:

答案 0 :(得分:3)

如果您首先将每对转换为具有以下内容的元组:

a = [tuple(item) for item in a]
b = [tuple(item) for item in b]

然后你可以简单地在两者之间取集union

c = set(a).union(b)

这将为您提供一个集合,其中每个集合中的一个在集合中的任何一个或两个集合中至少出现一次:

>>> c
{(1.0, 2.0), (3.0, 4.0), (2.0, 3.0), (1.0, 4.0)}

如果您希望此行为保持倍数,则只需将Counter替换为set,然后您可以将它们全部带回.elements()

的一个集合中
from collections import Counter
a = [[2.0, 3.0], [1.0, 2.0] , [2.0, 3.0]]
b = [[1.0, 4.0], [2.0, 3.0] , [3.0, 4.0], [2.0, 3.0]]
a1 = Counter(map(tuple,a))
b1 = Counter(map(tuple,a))
c = a1 | b1

>>> c
Counter({(2.0, 3.0): 2, (1.0, 2.0): 1, (1.0, 4.0): 1, (3.0, 4.0): 1})
>>> list(c.elements())
[(2.0, 3.0), (2.0, 3.0), (1.0, 2.0), (1.0, 4.0), (3.0, 4.0)]

答案 1 :(得分:1)

此解决方案效率可能不高,但可能会产生结果:

a = [[2.0, 3.0], [1.0, 2.0] , [2.0, 3.0]]
b = [[1.0, 4.0], [2.0, 3.0] , [3.0, 4.0]]
c = []

for item in a:
    if item not in c:
        c.append(item)

for item in b:        
    if item not in c:
        c.append(item)

print(c)

输出:

[[2.0, 3.0], [1.0, 2.0], [1.0, 4.0], [3.0, 4.0]]

答案 2 :(得分:0)

或者,您可以使用itertools groupby

a = [[2.0, 3.0], [1.0, 2.0] , [2.0, 3.0]]
b = [[1.0, 4.0], [2.0, 3.0] , [3.0, 4.0]]

import itertools
c = [k for k,g in itertools.groupby(sorted(a+b))]

will result in

[[1.0, 2.0], [1.0, 4.0], [2.0, 3.0], [3.0, 4.0]]
相关问题