python的新手 - 有人能告诉我我做错了吗?
我需要编写一个函数,它接受未知数量的参数并返回一个唯一的列表。 例如:
a= ['mary', 'james', 'john', 'john']
b= ['elsie', 'james', 'elsie', 'james']
unique_list(a,b)
['mary', 'james','john', 'elsie']
这是我进行一些研究后的一些代码,但输出并不是我需要的:
def unique_list:(*something)
result1= list(something)
result = ' '.join(sum(result1, []))
new= []
for name in result:
if name not in new:
new.append(name)
return new
>>> unique_list(a,b) ['m', 'a', 'r', 'y', ' ', 'j', 'e', 's', 'o', 'h', 'n', 'l', 'i']
这是我累了的另一个:
def unique_list(*something):
result= list(something)
new=[]
for name in result:
if name not in new:
new.append(name)
return new
>>> unique_list(a,b) [['mary', 'james', 'john', 'john'], ['elsie', 'james', 'elsie', 'james']]
另一个,但我收到一条错误消息:
def single_list(*something):
new=[]
for name in something:
if name not in new:
new.append(name)
new2= list(set(new))
return new2
>>> single_list(a,b) Traceback (most recent call last): File "", line 1, in single_list(a,b) File "", line 6, in single_list new2= list(set(new)) TypeError: unhashable type: 'list'
有什么想法吗?提前感谢您的帮助。
答案 0 :(得分:5)
您可以使用set
:
def unique_list(a, b):
return list(set(a + b))
对于未知数量的参数,您可以将所有列表与reduce
:
import operator
def unique_list(*args):
return list(set(reduce(operator.add, args)))
输出:
>>> a= ['mary', 'james', 'john', 'john']
>>> b= ['elsie', 'james', 'elsie', 'james']
>>> unique_list(a, b)
['james', 'john', 'mary', 'elsie']
答案 1 :(得分:3)
您想要未知数量的参数:
In [73]: import itertools
In [74]: def func(*args):
...: return set(itertools.chain(*args))
In [75]: func([1,2,3,4],[3,4,5],[1,2])
Out[75]: set([1, 2, 3, 4, 5])
或没有itertools:
In [77]: def func2(*args):
...: setlist=[set(i) for i in args]
...: return set.union(*setlist)
In [78]: func2([1,2,3,4],[3,4,5],[1,2])
Out[78]: set([1, 2, 3, 4, 5])
答案 2 :(得分:3)
在你第二次尝试时,你几乎做对了。
实际上,在代码的那一部分,您将每个列表视为一个元素。您可能想要考虑列表中的每个元素。所以你的代码可能是:
def unique_list(*something):
result= list(something)
new=[]
for names in result:
for name in names:
if name not in new:
new.append(name)
return new
那就是结果:
['mary', 'james', 'john', 'elsie']
同样适用于您的第三次尝试。请注意,在这种情况下,从列表中创建一个集合,然后从该集合中创建一个列表可能不会返回与原始列表顺序相同的元素。
根据您的需要,您还可以使用itertools.chain()。功能是:
import itertools
def unique_list(*something):
return list(set(itertools.chain(*something)))
结果将是(记住集合不保留原始顺序):
['james', 'john', 'mary', 'elsie']
答案 3 :(得分:1)
您可以连接所有lists
,然后从生成的set
创建list
。这适用于任何数量的传入列表,其中函数看起来像def unique_lists( *lists )
ret_list = []
for l in lists:
ret_list = ret_list + l
return set( ret_list )
答案 4 :(得分:1)
a= ['mary', 'james', 'john', 'john']
b= ['elsie', 'james', 'elsie', 'james']
def unique_list(a, b):
a.extend(b)
return list(set(a))
答案 5 :(得分:0)
您正在寻找的功能(我认为)是制作一组两个列表的组合,然后再将它组成一个列表。像这样:
list(set(list(a+b)))
给出:['james', 'john', 'mary', 'elsie']