Python3.3函数将多个列表中的唯一值合并为一个列表
我对Python非常陌生。我正在尝试编写一个函数,将单独列表中的唯一值合并到一个列表中。我不断得到一组列表的结果。最后,我想从我的三个列表中得到一个唯一值列表——a、b、c。谁能帮我一下吗Python3.3函数将多个列表中的唯一值合并为一个列表,python,list,function,merge,python-3.3,Python,List,Function,Merge,Python 3.3,我对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]
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])
您可能只需要设置:
>>> 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}
如果您确实关心原始顺序(在本例中,集合恰好保留了它,但不能保证保留),那么您可以通过认识到参数list
包含传入的所有原始列表的元组来修复原始尝试。这意味着,通过迭代,您可以一次获得一个列表,而不是其中的元素-您可以使用itertools模块修复此问题:
for x in itertools.chain.from_iterable(lists):
if x not in newlist:
newlist.append(x)
此外,您希望
newlist
以空列表开始,而不是输入列表的副本。处理动态生成的列表
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)
一个常见的用例是动态生成列表列表,每个子列表有时具有任意长度:
import random
abc, values = [], ["a", "b", "c", "d"]
for i in range(3):
l = []
for j in range(3):
l.append(values[random.randint(0, len(values) - 1)])
abc.append(l)
如果你在处理一个列表,按照g.d.d.c.的建议简单地求和是行不通的。即:
uniques = set( a + b + c )
出现这种问题的原因是,您必须特别参考列表a
、b
和c
。Ivc的答案非常好,让我们更接近:
set().union(a, b, c)
但同样,您必须明确地引用您的列表
解决方案
要从任意长度的列表列表中获取唯一值,可以使用:
它将返回无序的适当值(例如
[“d”、“b”、“a”、“d”]
)+1,以便使用union,而不是事先将列表添加到一起。这意味着您可以使用其他iterables而不仅仅是列表。请注意,根据唯一值的数量,每次迭代检查x not in newlist
的时间都会增加。
import random
abc, values = [], ["a", "b", "c", "d"]
for i in range(3):
l = []
for j in range(3):
l.append(values[random.randint(0, len(values) - 1)])
abc.append(l)
# The Important Line Below
unique = set().union(*abc)
print(unique)