Skip to content

Instantly share code, notes, and snippets.

@ericzhong
Created May 17, 2017 12:28
Show Gist options
  • Save ericzhong/dc8505a1bd11d9c6106d18a605be3d08 to your computer and use it in GitHub Desktop.
Save ericzhong/dc8505a1bd11d9c6106d18a605be3d08 to your computer and use it in GitHub Desktop.
统计列表中各元素出现的次数
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