Python 3.3将多个列表中的唯一值合并到一个lis的函数

2024-04-28 09:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不太熟悉..我正在尝试编写一个函数,将单独列表中的唯一值合并到一个列表中。我总是得到一组列表的结果。最后,我想从我的三个列表-a,b,c中得到一个唯一值的列表。有人能帮我一把吗?

def merge(*lists):
    newlist = lists[:]
    for x in lists:
        if x not in newlist:
            newlist.extend(x)
    return newlist

a = [1,2,3,4]
b = [3,4,5,6]
c = [5,6,7,8]

print(merge(a,b,c))

我得到一组名单

([1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8])

Tags: 函数in列表forreturnifdefnot
3条回答
def merge(*lists):
    newlist = []
    for i in lists:
            newlist.extend(i)
    return newlist

merge_list = merge(a,b,c,d)

merge_list = set(merge_list)

merge_list = list(merge_list)

print(merge_list)

您可能只需要设置:

>>> a = [1,2,3,4]
>>> b = [3,4,5,6]
>>> c = [5,6,7,8]
>>>
>>> uniques = set( a + b + c )
>>> uniques
set([1, 2, 3, 4, 5, 6, 7, 8])
>>>

如果您不关心它们的原始顺序,最简单、最快捷的方法是使用set函数:

>>> set().union(a, b, c)
{1, 2, 3, 4, 5, 6, 7, 8}

如果您关心原始顺序(在这种情况下,集合恰好保留了它,但不能保证),那么您可以通过认识到参数lists包含您传入的所有原始列表的元组来修复您的原始尝试。这意味着遍历它可以一次获取这些列表中的每个列表,而不是其中的元素—您可以使用itertools模块来解决这个问题:

for x in itertools.chain.from_iterable(lists):
   if x not in newlist:
      newlist.append(x)

另外,您希望newlist以空列表而不是输入列表的副本开始。

相关问题 更多 >