Connecting Tech Pros Worldwide Help | Site Map

about array

Newbie
 
Join Date: Jul 2009
Posts: 8
#1: Aug 22 '09
if there are same elements in the list, how can i take them away and make the list unique..... somethings like array_unique in PHP.... i have consult this web site, but it doesn't talk about it
http://www.java2s.com/Code/Python/List/CatalogList.htm
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,561
#2: Aug 22 '09

re: about array


Here's one way:
Expand|Select|Wrap|Line Numbers
  1. >>> some_list = [1,1,1,2,2,2,3,3,3]
  2. >>> unique_list = []
  3. >>> for item in some_list:
  4. ...     if item not in unique_list:
  5. ...         unique_list.append(item)
  6. ...         
  7. >>> unique_list
  8. [1, 2, 3]
  9. >>> 
If you are using Python 2.4 or higher:
Expand|Select|Wrap|Line Numbers
  1. >>> set(some_list)
A set can contain only unique elements. A set can be converted back to a list.
kudos's Avatar
Expert
 
Join Date: Jul 2006
Location: Norway
Posts: 110
#3: Aug 23 '09

re: about array


I would do something like this:

Expand|Select|Wrap|Line Numbers
  1. a = [1,1,1,1,2,3,3,3,3,4]
  2. b = {}
  3. for aa in a:
  4.  b[aa] = 1
  5. print b.keys() 
  6.  
Quote:

Originally Posted by weskam View Post

if there are same elements in the list, how can i take them away and make the list unique..... somethings like array_unique in PHP.... i have consult this web site, but it doesn't talk about it
http://www.java2s.com/Code/Python/List/CatalogList.htm

Newbie
 
Join Date: Jul 2009
Posts: 8
#4: Aug 23 '09

re: about array


Thanks very much, both of them work
Reply