I have a list:
a = [1, 2, 6, 4, 3, 5, 7]
Please, explain to me how to check whether e开发者_Go百科lement appears only once in in the list?
Please, also explain if all elements from 1 to len(a)
are in the list. For instance, in list 'a' element from 1 to 7 are in the list, but if the list is b = [1, 4, 3, 5]
, then not all elements from 1 to 4 are not in the list.
Thank you!
When I read your question, I took a different meaning from it than mark did. If you want to check if a particular element appears only once, then
def occurs_once(a, item):
return a.count(item) == 1
will be true only if item
occurs in the list exactly once.
See Pokes answer for the second question
len( set( a ) ) == len( a )
for the first question, and
( len( set( a ) ) == len( a ) == max( a ) ) and min( a ) == 1
for the second.
For your first question if your elements are hashable you can create a set containing the elements and check its length:
len(set(a)) == len(a)
Alternatively you can use this function which can give better performance than the above if the result is False (but worse performance when the result is True):
def are_all_elements_unique(l):
seen = set()
for x in l:
if x in seen:
return False
seen.add(x)
return True
For the second question you might want to check
sorted(a) == range(1, len(a) + 1)
i understood you want something like that:
[x for x in a if a.count(x) == 1]
精彩评论