Python 我需要帮助在我的代码中形成if-else条件
我需要在代码中形成if-else条件。我将两个列表相互比较,如果每个列表中有任何不同的项目或没有任何项目,则打印。我的代码如下Python 我需要帮助在我的代码中形成if-else条件,python,python-3.x,loops,Python,Python 3.x,Loops,我需要在代码中形成if-else条件。我将两个列表相互比较,如果每个列表中有任何不同的项目或没有任何项目,则打印。我的代码如下 title_check = [[y for y in xml_title_list if y not in json_title_list], [y for y in json_title_list if y not in xml_title_list]] if len(title_check [0]): print("Type which are unmatc
title_check = [[y for y in xml_title_list if y not in json_title_list], [y for y in json_title_list if y not in xml_title_list]]
if len(title_check [0]):
print("Type which are unmatched in XML are ", title_check [0])
if len(title_check [1]):
print("Type which are unmatched in JSON are ", type_check[1])
else:
print("No Unmatched type found")
我想将这两种条件结合起来,并希望每次都运行它。如果他们不执行,我还想要别的。现在,它只对第二个if条件使用else条件。
有人能帮我吗?提前感谢您可以使用另一个答案中显示的标志。另一种方法是
title_check = [[y for y in xml_title_list if y not in json_title_list], [y for y in json_title_list if y not in xml_title_list]]
is_xml = False
if len(type_check[0]):
is_xml = True
print("Type which are unmatched in XML are ", type_check[0])
is_json = False
if len(type_check[1]):
is_json = True
print("Type which are unmatched in JSON are ", type_check[1])
if (not is_xml) and (not is_json):
print("No Unmatched type found")
如果len(title\u check[0])或len(title\u check[1]):
如果len(标题检查[0]):
打印(“XML中不匹配的类型为”,类型为检查[0])
如果len(标题检查[1]):
打印(“JSON中不匹配的类型为”,类型为\u check[1])
其他:
打印(“未找到不匹配的类型”)
您可以使用另一个答案中显示的标志。另一种方法是
如果len(title\u check[0])或len(title\u check[1]):
如果len(标题检查[0]):
打印(“XML中不匹配的类型为”,类型为检查[0])
如果len(标题检查[1]):
打印(“JSON中不匹配的类型为”,类型为\u check[1])
其他:
打印(“未找到不匹配的类型”)
您可以使用set.difference
:
xml, json = set(xml_title_list), set(json_title_list)
umatched_xml = json - xml
unmatched_json = xml - json
if umatched_xml or unmatched_json:
if umatched_xml:
print("Type which are unmatched in XML are ", umatched_xml)
if umatched_json:
print("Type which are unmatched in JSON are ", umatched_json)
else:
print("No unmatched type found")
您可以使用
set.difference
:
xml, json = set(xml_title_list), set(json_title_list)
umatched_xml = json - xml
unmatched_json = xml - json
if umatched_xml or unmatched_json:
if umatched_xml:
print("Type which are unmatched in XML are ", umatched_xml)
if umatched_json:
print("Type which are unmatched in JSON are ", umatched_json)
else:
print("No unmatched type found")
你可以用一个booleanTrue@Sanketh来实现这一点,但我们不知道xml和json是否都是OP需要处理的类型,所以我更喜欢一种模块化/可扩展的方法。你可以用一个booleanTrue@Sanketh来实现这一点,但我们不知道xml和json是否都是OP需要处理的类型,所以我更喜欢一种更模块化/可扩展的方法。虽然我已经找到了答案,但您的方法很好。仍然需要解决我的问题,如果条件都为假,并且我必须打印“没有不匹配的类型”,我将把else条件放在哪里?虽然我已经找到了答案,但您的方法是好的。仍然需要解决我的问题,如果条件都为false,并且我必须打印“没有不匹配的类型”,那么我将把else条件放在哪里呢?