如何通过循环传递 isinstance 中的元组? [复制]
Posted
技术标签:
【中文标题】如何通过循环传递 isinstance 中的元组? [复制]【英文标题】:How can i pass tuples in isinstance through loop? [duplicate] 【发布时间】:2018-09-11 18:16:04 【问题描述】:我的代码:
def validate_record_schema():
"""Validate that the 0 or more Payload dicts in record
use proper types"""
err_path = "root"
try:
for record in test1:
for device in record.get('Payload', []):
payload = device.get('Payload', None)
if payload is None:
continue
device = payload["Device"]
key_data = ((device["ManualAdded"],bool), (device["Location"],str))
for i in key_data:
if not isinstance(i):
return False
except KeyError as err_path:
print("missing key")
return False
return True
print(validate_record_schema())
我想像下面那样做,但我做不到。
key_data = ((device["ManualAdded"],bool), (device["Location"],str))
for i in key_data:
if not isinstance(i):
return False
如果我像下面那样做,它正在工作
if not isinstance((device["ManualAdded"],bool)):
return False
但我需要像上面那样做。我该怎么做?
Json 数据
test1 = ['Id': '12', 'Type': 'DevicePropertyChangedEvent', 'Payload': ['DeviceType': 'producttype', 'DeviceId': 2, 'IsFast': False, 'Payload': 'DeviceInstanceId': 2, 'IsResetNeeded': False, 'ProductType': 'product'
, 'Product': 'Family': 'home', 'Device': 'DeviceFirmwareUpdate': 'DeviceUpdateStatus': None, 'DeviceUpdateInProgress': None, 'DeviceUpdateProgress': None, 'LastDeviceUpdateId': None, 'ManualAdded': False,
'Name': 'Value': 'Jigital60asew', 'IsUnique': True, 'State': None, 'Location': "dg", 'Serial': None, 'Version': '2.0.1.100']]
【问题讨论】:
【参考方案1】:您可以使用*
运算符扩展元组并将其成员作为单独的参数传递。
key_data = (('This is a string', str), ('This is a string', bool))
for i in key_data:
if isinstance(*i):
print("yes")
else:
print("no")
【讨论】:
它正在工作..谢谢...我可以检查类型是 'str' 还是 'None' 像 (('This is a string', str or None), ('This is a string ', bool)) 我可以像我在评论部分提到的那样做吗?请回复 这是一个单独的问题,但可以。但是,您不使用or
表达式,而是将类型元组作为第二个参数传递给isinstance()
。使用与此问题相同的元组扩展,i = (variable, (str, type(None)))
/ if isinstance(*i):
。以上是关于如何通过循环传递 isinstance 中的元组? [复制]的主要内容,如果未能解决你的问题,请参考以下文章