将列表转换为集合和联合操作

时间:2015-10-11 15:16:15

标签: python list union

def count1(x,s):
    def loop(x,s,count):
        while s!=[]:
            if x == s[0]:
                return loop(x,s[1:],count + 1)
            else:
                return loop(x,s[1:],count)
        if s==[]:
            return count
    return loop(x,s,0)

def remove_all1(x,s):
    def loop(x,s,ss):
        while s!=[]:
            if x == s[0]:
                return loop(x,s[2:],ss+[s[1]])
            else:
                return loop(x,s[1:],ss+[s[0]])
        return ss
    return loop(x,s,[])

def union0(xs,ys):
    ss = xs + ys
    for i in ss:
        #print(i)
        if count1(i,ss) > 1:
            return [ss[i]] + remove_all1(i,ss)
    return ss

print(union0([1,7,5,6],[9,9,0,6,4]))

这将打印[0,1,7,5,9,9,0,4], 如何打印[0,1,7,5,9,0,4]?为了避免冗余,我知道set()方式,但只想知道使用count0()和remove_all1()方法。谢谢

2 个答案:

答案 0 :(得分:2)

我的解决方案。

import itertools
from collections import Counter

def union(*lists):
    joined = itertools.chain(*lists)  # joins all the arguments.
    counts = Counter(joined)  # counts elements in list.
    result = []
    for item, count in counts.items():
        if count >= 1:  # or any number you need
            result.append(item)  # or yield it.
    return result

print(union([1, 7, 5, 6], [9, 9, 0, 6, 4], [1, 2]))

结果:

[0, 1, 2, 4, 5, 6, 7, 9]

还有一些文档:

答案 1 :(得分:2)

在将所有内容映射到集后,您可以set.union

def union(*lsts):
    return list(set.union(*map(set, lsts)))

输出:

In [2]: union([1, 7, 5, 6], [9, 9, 0, 6, 4], [1, 2])
Out[2]: [0, 1, 2, 4, 5, 6, 7, 9]

或者,如果您想要首次出现的订单:

from collections import OrderedDict
from itertools import chain
def union(*lsts):
    return list(OrderedDict.fromkeys(chain(*lsts)))

或者为了维持秩序,您也可以随时创建该组:

from itertools import chain
def union(*lsts):
    st = set()
    for ele in chain(*lsts):
        if ele not in st:
            yield ele
        st.add(ele)

使用Counter dict来获取列表中所有元素的并集是绝对没有意义的,如果你试图保持出现的元素< n次然后才有意义。