Connecting Tech Pros Worldwide Help | Site Map

How to delete unique items in an array

Newbie
 
Join Date: Aug 2009
Posts: 5
#1: Aug 25 '09
Hi

I need to write a program and part it's functionality is to delete unique items in an array. That is, delete items in the array that only occur once.

I also need to delete the first occurrence of repeated items, and I'm pretty sure the solution to these two will go hand in hand.

Thanks

akadeco
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#2: Aug 25 '09

re: How to delete unique items in an array


akadeco,

Are you asking for help with your assignment? We can't help until you show some effort to solve this yourself.

BV
Moderator
kudos's Avatar
Expert
 
Join Date: Jul 2006
Location: Norway
Posts: 110
#3: Aug 25 '09

re: How to delete unique items in an array


(I guess the assignment is too small to be a school assignment)

Expand|Select|Wrap|Line Numbers
  1. a = [1,2,3,4,3,4,4,4,5,6]
  2. b = {}
  3. i = 0
  4. for c in range(len(a)):
  5.  if(b.has_key(a[i]) == False):
  6.   b[a[i]] = 1
  7.   a.remove(a[i])
  8.  else: 
  9.   i+=1
  10. print a
  11.  
-kudos


Quote:

Originally Posted by akadeco View Post

Hi

I need to write a program and part it's functionality is to delete unique items in an array. That is, delete items in the array that only occur once.

I also need to delete the first occurrence of repeated items, and I'm pretty sure the solution to these two will go hand in hand.

Thanks

akadeco

bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#4: Aug 25 '09

re: How to delete unique items in an array


Here's another way that creates a new list.
Expand|Select|Wrap|Line Numbers
  1. >>> a = [1,2,3,4,3,4,4,4,5,6]
  2. >>> b = []
  3. >>> for j, item in enumerate(a):
  4. ...     if a.count(item) > 1 and j > a.index(item):
  5. ...         b.append(item)
  6. ...         
  7. >>> b
  8. [3, 4, 4, 4]
  9. >>> 
kudos's Avatar
Expert
 
Join Date: Jul 2006
Location: Norway
Posts: 110
#5: Aug 25 '09

re: How to delete unique items in an array


Expand|Select|Wrap|Line Numbers
  1. a = [1,2,3,4,3,4,4,4,5,6]
  2. b=[]
  3. for c in a:
  4.  if(a.count(c) >=2 and b.count(c) < a.count(c)-1):
  5.   b.append(c)
  6. print b 
  7.  
Can we avoid using the list 'b'?

-kudos
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#6: Aug 25 '09

re: How to delete unique items in an array


With a list comprehension:
Expand|Select|Wrap|Line Numbers
  1. >>> a = [item for j, item in enumerate(a) if a.count(item) > 1 and j > a.index(item)]
  2. >>> a
  3. [3, 4, 4, 4]
  4. >>> 
Newbie
 
Join Date: Aug 2009
Posts: 5
#7: Aug 26 '09

re: How to delete unique items in an array


@Kudos thank you so much that is exactly what I needed!

Thank you all for your swift replies
Reply

Tags
delete unique items array