Skip to main content
 首页 » 编程设计

Python-创建一个函数以从未知数量的参数中获取唯一列表

2025年05月04日10qq号

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'] 

This is another one I have tired:

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']] 

Another one but I got an error message:

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' 

有什么想法吗?预先感谢您的所有帮助。

请您参考如下方法:

您可以使用 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']