首页 > 解决方案 > 如何检查某些元素是否在python的代码中

问题描述

这就是我的意思,假设我正在检查某个电话号码属于哪个电话接线员

tel = input("Enter telephone number: ")

# Say I want to check if 077, #0782, 0783, 070 are in the user input
# Say the telephone numbers [0782123123, 078312312, 07712312] 
# which belong to Operator1 are entered by the user 
# I want be able to sort out the user's input 

if 0783, 077, 070,0782 are in tel: 
  Then print ("This number belongs to Operator 1")

and if 0755, 0723 are in tel:
   Then print ("This number belongs to Operator 2")

标签: python

解决方案


您可以使用内置功能any

tel = input("Enter telephone number: ")

if any(num in tel for num in ('0783', '077', '070','0782')):
  print ("This number belongs to Operator 1")

if any(num in tel for num in ('0755', '0723')):
   print ("This number belongs to Operator 2")

推荐阅读