I'm trying to print all elements in a sorted list that only occur once .
My code below works but I'm sure there is a better way:
def print_unique(alist):
i = 0
for i in range(len(alist)):
if i < (len(alist)-1):
if alist[i] == alist[i+1]:
i+=1
if alist[i] == alist[i-1]:
i+=1
elif alist[i] == alist[i-1]:
i+=1
else:
print alist[i]
else:
if alist[-1]!= alist[-2]:
print alist[-1]
randomlist= [1,2,3,3,3,4,4,5,6,7,7,7,7,8,8,8,9,11,12,14,42]
print_unique(randomlist)
This produces
1
2
5
6
9
11
12
14
42
eg all values that only appear once in a row.
You could use the itertools.groupby()
function to group your inputs and filter on groups that are one element long:
from itertools import groupby
def print_unique(alist):
for elem, group in groupby(alist):
if sum(1 for _ in group) == 1: # count without building a new list
print elem
or if you want to do it 'manually', track the last item seen and if you have seen it more than once:
def print_unique(alist, _sentinel=object()):
last, once = _sentinel, False
for elem in alist:
if elem == last:
once = False
else:
if once:
print last
last, once = elem, True
if last is not _sentinel and once:
print last
You may want to replace the print
statements with yield
and leave printing to the caller:
def filter_unique(alist):
for elem, group in groupby(alist):
if sum(1 for _ in group) == 1: # count without building a new list
yield elem
for unique in filter_unique(randomlist):
print unique
This question seems to have duplicates.
If you do not wish to preserve the order of your list, you can do
print list(set(sample_list))
You can also try,
unique_list = []
for i in sample_list:
if i not in unique_list:
unique_list.append(i)
EDIT:
In order to print all the elements in the list so that they appear once in a row, you can try this
print '\n'.join([str(i) for i in unique_list])
And, as @martijn-pieters mentioned it in the comments, the first code was found to be very fast compared to the second one, when I did a small benchmark. On a list of 10^5 elements, the second code took 63.66 seconds to complete whereas the first one took a mere 0.2200 seconds. (on a list generated using random.random()
)
you can do by this:
print (set(YOUR_LIST))
or if you need a list use this:
print (list(set(YOUR_LIST)))
Sets are lists containing unique items. If you construct a set from the array, it will contain only the unique items:
def print_unique(alist):
print set( alist )
The input list does not need to be sorted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.