Created
May 17, 2017 12:28
-
-
Save ericzhong/dc8505a1bd11d9c6106d18a605be3d08 to your computer and use it in GitHub Desktop.
统计列表中各元素出现的次数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def count(lst): | |
r = {} | |
for i in lst: | |
if i in r: | |
r[i] += 1 | |
else: | |
r[i] = 1 | |
return r | |
if __name__ == '__main__': | |
assert count([1,1,2,2,3,4]) == {1:2, 2:2, 3:1, 4:1} | |
assert count([1,1,'a','a']) == {1:2, 'a':2} | |
assert count([1]) == {1:1} | |
assert count([]) == {} | |
assert count(['ab','ab','bc']) == {'ab':2, 'bc':1} | |
print('Well Done!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment