Skip to content

Instantly share code, notes, and snippets.

@sincerefly
Created April 30, 2015 04:14
Show Gist options
  • Save sincerefly/076d60e26c58bbe3d2c7 to your computer and use it in GitHub Desktop.
Save sincerefly/076d60e26c58bbe3d2c7 to your computer and use it in GitHub Desktop.
判断列表中某一元素有多少个
# 这个是一个很程序化的写法,但是没有利用好python的特性
def number_of_occurrences(s, xs):
num = 0
for i in sorted(xs):
if i == s:
num += 1
return num
# 这种写法就很pythonic
def number_of_occurrences2(s, xs):
return xs.count(s)
print number_of_occurrences(2, [1, 2, 2, 3, 4, 5])
print number_of_occurrences2(2, [1, 2, 2, 3, 4, 5])
# result 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment