首页 > 解决方案 > Checking if value is in a list without using "in"

问题描述

I want to write a function that checks whether a 'value' is within a list. I have come up with a way to do it using "in" but now I want to find a way that works without using it.

My code with it looks like this:

def is_member(value, l):
    if value in l:
        print("is member")
        return True
    else: 
        print("not member")
        return False

and it works with all these asserts

assert is_member(2, [1, 2, 3])
assert not is_member(0, [1, 2, 3])
assert is_member('C', 'CATG')
assert not is_member('U', 'CATG')

In what way can I achieve the same thing (in a simple, beginner way) without using "in"?

标签: pythonstringlist

解决方案


利用count

它给出了一个项目在列表中出现的次数

如果计数 > 0,则表示特定项目在列表中!

代码:

def is_member(value, l):
    if l.count(value)>0:
        print("is member")
        return True
    else: 
        print("not member")
        return False
assert is_member(2, [1, 2, 3])
assert not is_member(0, [1, 2, 3])
assert is_member('C', 'CATG')
assert not is_member('U', 'CATG')

推荐阅读