python - 多字符串比较
问题描述
我在restapi中创建了一个调用来在一个数组中打印结果,但是我需要在保存这个结果之前比较这个数据,例如:
for id in ids:
try:
now = datetime.datetime.now()
token, tokenExpireDate = checkTokenExpireDate(apiUrl, client_id, client_secret, token, now, tokenExpireDate)
data = getHostDetails(apiUrl, token, id)['resources'][0]
local_ip = data['local_ip']
allowed_range_ip = ['10.20.*', '10.10.*', '172.12.*']
if local_ip in allowed_range_ip:
print(local_ip)
else:
print(local_ip)
except Exception as e:
print({'exception': e, 'id': id})
我想比较一下allowed_range_ip
,local_ip
如果保存在数组local_ip
中是真的allowed_range_ip
,我怎么能这样做?我是使用python的新手,所以放轻松:)
编辑:示例输出脚本(一些随机 IP),我只想打印类似于allowed_range_ip
:
10.160.20.02
172.17.0.9
10.255.250.68
10.80.10.20
解决方案
Python 的内置ipaddress模块使这很容易。您创建一个ip_network
对象,然后您可以查看给定对象ip_address
是否在该网络中。例如:
from ipaddress import ip_address, ip_network
allowed_range_ip = [
ip_network("10.20.0.0/16"),
ip_network("10.10.0.0/16"),
ip_network("172.12.0.0/16"),
]
local_ip1 = ip_address('10.20.30.40')
print(any(local_ip1 in net for net in allowed_range_ip))
local_ip2 = ip_address('10.21.30.40')
print(any(local_ip2 in net for net in allowed_range_ip))
推荐阅读
- java - 如何处理运动流记录?(多处理器)
- html - 如何将 1 个渐变变成多个元素
- ruby-on-rails - 条纹支付错误:必须提供来源或客户
- xamarin.forms - Xamarin.Forms Grid Column 的宽度没有填满整个单元格
- tensorflow - 模型不学习
- xaml - 是否可以访问 XAML 中自定义控件的内部控件?
- html - Youtube 嵌入式视频 (iframe) 仅在 Safari 中表现异常
- python-3.x - 使用Python反转句子中的单词
- c# - 我的玩家在使用盒子对撞机接触任何物体时死亡
- mongodb - 创建没有日期时间 pymongo 的 ISODATE