Note:
1.sorted()和sort()的区别: What is the difference between `sorted(list)` vs `list.sort()` ? python
sorted()
returns a new sorted list, leaving the original list unaffected. list.sort()
sorts the list in-place, mutating the list indices, and returns None
(like all in-place operations).
2.Counter object in Collections module
>>> c = Counter(['eggs', 'ham'])
>>> c['bacon'] # count of a missing element is zero
0
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1] # n least common elements
+c # remove zero and negative counts
=======================================================
题目:Write a function - duplicate_items
to find the redundant or repeated items in a list and return them in sorted order.
This method should return a list of redundant integers in ascending sorted order.
============================================================
我的code
def duplicate_items(list_numbers):
for ele in set(list_numbers):
list_numbers.remove(ele)
list_numbers.sort()
return list_numbers
有一个错误:list_numbers可能还有重复
list_numbers.sort()
return list_numbers
可改为
return sorted(set(list_numbers))
=================================================================
看看别人的code:
import collections
def duplicate_items(list_numbers):
return [item for item, count in collections.Counter(list_numbers).items() if count > 1]
根据上面列出的counters object的方法中的items()
c.items() # convert to a list of (elem, cnt) pairs
if count in the list of pairs(item,count)>1:
return the item.
the pairs are created by collections.Counter(list_numbers).items()
-------------------------------------------------------------------------------------------------------
另外一个比较好理解的:
def duplicate_items(list_numbers):
set_list = set(list_numbers)
return [i for i in set_list if list_numbers.count(i)>1]
我怎么总是不会用 comprehension呢?但是list.count()的时间复杂度是O(n),他这岂不是O(n^2)了?