python - 如何检查号码是否与列表中的号码相同
问题描述
我想检查用户输入的数字是否与列表中的数字相同,以及我使用 for 循环选择列表中的项目以与数字进行比较的方式不起作用。就像它只是遍历列表中的第一项。即使我输入 43(示例),它仍然会打印(列表中有 43),我认为第一项是 65,这与 43 不同。
ARR = [65,75,85,95,105]
def check_number ():
NUM = int (input ("Please enter the number you want to check with"))
for x in range (len (arr)):
check == ARR [x]
if check == ARR [x]:
print (NUM,"is available in the list")
else:
print (NUM,"is not available is the list")
check_number ()
解决方案
检查一个值(包括数字和字符串的任何可散列值)是否是列表成员的更好方法是使用 Python 的内置set
类型:
arr = set([65, 75, 85, 95, 105])
def check_number():
num = int (input ("Please enter the number you want to check with"))
if num in arr:
print (num, "is available in the list")
else:
print (num, "is not available is the list")
check_number ()
对于更大的数据集,它既更省时,也更惯用。
推荐阅读
- azure - 在 Azure Devops SSH 任务中运行“sudo”命令的安全方式
- java - 使用 gradle 和 java 在 github 项目中添加“Used by”
- python - 如何使用python将图像中方形标题的背景从黑色反转为白色?
- python - 仅对数组中的单个值进行排序
- oracle - Apex Oracle 中 P1_item1 和 P1_Item2 之间的区别
- html - CSS 元素在浏览器窗口中的纵横比和位置缩放
- parsing - 如何解析golang时间
- r - 在 S3 中模拟多个调度(用于 3 个签名参数)
- github - 如何在 Github Actions 中失败?
- google-apps-script - GAS 未在网页中获取邮件图像:收到错误“ERR_UNKNOWN_URL_SCHEME”