JJo*_*eph 1 python function unique
python的新手 - 有人能告诉我我做错了什么吗?
我需要编写一个函数,它接受未知数量的参数并返回一个唯一的列表.例如:
a= ['mary', 'james', 'john', 'john']
b= ['elsie', 'james', 'elsie', 'james']
unique_list(a,b)
['mary', 'james','john', 'elsie']
Run Code Online (Sandbox Code Playgroud)
这是我进行一些研究后的一些代码,但输出不是我需要的:
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
Run Code Online (Sandbox Code Playgroud)
>>> 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
Run Code Online (Sandbox Code Playgroud)
>>> 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
Run Code Online (Sandbox Code Playgroud)
>>> 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))
Run Code Online (Sandbox Code Playgroud)
对于未知数量的参数,您可以将所有列表与以下内容一起添加reduce
:
import operator
def unique_list(*args):
return list(set(reduce(operator.add, args)))
Run Code Online (Sandbox Code Playgroud)
这输出:
>>> a= ['mary', 'james', 'john', 'john']
>>> b= ['elsie', 'james', 'elsie', 'james']
>>> unique_list(a, b)
['james', 'john', 'mary', 'elsie']
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1258 次 |
最近记录: |