简体   繁体   中英

I need the element that appears only occur once

I need the element that appears only occur once. (python)

For example the result for

mylist = ['a', 'a', 'a', 'a', 'b', 'c']

would be

2

You can use collections.Counter to count the number of occurrences of each distinct item, and retain only those with a count of 1 with a generator expression:

from collections import Counter
sum(1 for c in Counter(mylist).values() if c == 1)

This returns: 2

This situation looks like a pure Set structure. If I were you I would turn the array to set and check the size of it.

You can check examples how to do it here

You basically want to iterate through the list and check to see how many times each element occurs in the list. If it occurs more than once, you don't want it but if it occurs only once, you increase your counter by 1.

count = 0

for letter in mylist:
  if mylist.count(letter) == 1:
    count += 1

print (count)

This should work for you:

len(set(mylist))

It does require your values to be hashable.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM