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