将列表转换为集合并进行并集操作

3
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个回答

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,因此循环是完全多余的。 - Padraic Cunningham
这与list(set(itertools.chain(*lists)))完全等价,只是它保留了每个项的出现次数,然后将计数丢弃。此外,union函数的最后五行相当于return counts.keys() - jbg

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)

如果您想保留出现次数< n的元素,则使用Counter字典获取列表中所有元素的并集完全没有意义。


set.union 的例子基本上与 list(set(itertools.chain(*lsts))) 相同。 - jbg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接