How to delete unique items in an array | Newbie | | Join Date: Aug 2009
Posts: 5
| | |
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
|  | Moderator | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,560
| | | 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
|  | Expert | | Join Date: Jul 2006 Location: Norway
Posts: 110
| | | re: How to delete unique items in an array
(I guess the assignment is too small to be a school assignment) -
a = [1,2,3,4,3,4,4,4,5,6]
-
b = {}
-
i = 0
-
for c in range(len(a)):
-
if(b.has_key(a[i]) == False):
-
b[a[i]] = 1
-
a.remove(a[i])
-
else:
-
i+=1
-
print a
-
-kudos Quote:
Originally Posted by akadeco 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 |  | Moderator | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,560
| | | re: How to delete unique items in an array
Here's another way that creates a new list. - >>> a = [1,2,3,4,3,4,4,4,5,6]
-
>>> b = []
-
>>> for j, item in enumerate(a):
-
... if a.count(item) > 1 and j > a.index(item):
-
... b.append(item)
-
...
-
>>> b
-
[3, 4, 4, 4]
-
>>>
|  | Expert | | Join Date: Jul 2006 Location: Norway
Posts: 110
| | | re: How to delete unique items in an array -
a = [1,2,3,4,3,4,4,4,5,6]
-
b=[]
-
for c in a:
-
if(a.count(c) >=2 and b.count(c) < a.count(c)-1):
-
b.append(c)
-
print b
-
Can we avoid using the list 'b'?
-kudos
|  | Moderator | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,560
| | | re: How to delete unique items in an array
With a list comprehension: - >>> a = [item for j, item in enumerate(a) if a.count(item) > 1 and j > a.index(item)]
-
>>> a
-
[3, 4, 4, 4]
-
>>>
| | Newbie | | Join Date: Aug 2009
Posts: 5
| | | 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
|  | | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 226,223 network members.
|