python - 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"?
解决方案
利用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')
推荐阅读
- html - 如何调整org2html中的图像大小?
- spring - Kotlin - 使用接口类型的数据类
- javascript - Onscroll 切换无法添加或删除类
- python-3.x - 错误导致玩家与前两个障碍物发生碰撞,仅此而已
- python - GCloud Upload httplib2.RedirectMissingLocation: 重定向但响应缺少 Location: 标头
- xml - 使用 powershell 解析 XML 会给出“需要命名空间管理器或 XsltContext”错误
- vim - 我将如何映射新的运营商密钥?
- javascript - 如何将图像上传到 ExpressJS 服务器
- php - 代码问题:用于运行 php 脚本执行存储过程的 cPanel cron 作业
- java - AmazonS3ClientBuilder 没有响应