def count(squence,item):
count=0
i=0
for item in squence:
if item == squence:
count+=1
print count
count([1,7,8,7,7],7)
I don't understand why the If statment doesn't work :( Thanks,
list
already has a function count()
: [1,7,8,7,7].count(7)
returns 3
But what you are trying to do is:
def count(squence, item):
cnt = 0
for i in squence:
if i == item:
cnt += 1
print cnt
In your code, you overwrite item
: item
is the value you want to count but it is also the values you check, so it does not work...
You are overwriting your the variables your trying to check against. Also you need to compare the target item to the item that is in the sequence. The code below works.
def count(squence,target):
count=0
i=0
for item in squence:
if target == item:
count+=1
print count
count([1,7,8,7,7],7)
why not use the count method in python? Unless you are doing this as an exercise it makes sense to use pythons standard functions, right?
>>> mylist=[1,7,8,7,7]
>>> mylist.count(7)
3
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.