How do I make a function that returns a list of unique strings, given a list of strings with duplicates? [duplicate]

StackOverflow https://stackoverflow.com/questions/22953723

문제

This is a piece of homework for my programming course. We are asked to make a function that accepts a list of strings as a parameter, and then returns the same list of strings but without duplicates.
e.g:

>>> unique_list(['dog','cat','dog','fish'])
['dog','cat','fish']

Any information regarding the matter would be greatly appreciated.

도움이 되었습니까?

해결책

Use the following code:

>>> def unique_list(mylist):
...     copy = []
...     for k in mylist:
...             if k not in copy:
...                     copy.append(k)
...     return copy
... 
>>> unique_list([1])
[1]
>>> unique_list([1, 1])
[1]
>>> unique_list([1, 1, 2])
[1, 2]
>>> unique_list([1, 3, 1, 2])
[1, 3, 2]
>>> unique_list(['dog','cat','dog','fish'])
['dog', 'cat', 'fish']

The for loop loops over every item in mylist. If the item is already in copy, it does nothing. Otherwise, it adds the item to copy. At the end, we return the 'unduplicatified' version of mylist, stored in copy.

Or a one-liner would be:

>>> def unique_list(mylist):
...     return list(set(mylist))
... 
>>> unique_list([1])
[1]
>>> unique_list([1, 1])
[1]
>>> unique_list([1, 1, 2])
[1, 2]
>>> unique_list([1, 3, 1, 2])
[1, 2, 3]
>>> unique_list(['dog','cat','dog','fish'])
['fish', 'dog', 'cat'] 

다른 팁

def unique_list(subject):
    return list(set(subject))

This is what you can write in python 3.3

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top