Python 判断数组中是否存在特定元素:'SUB-SECURITY' 和 'SUB-OPERATOR'
判断数组中是否存在'SUB-SECURITY' 和 'SUB-OPERATOR',可以使用以下两种方法:
-
循环遍历数组:
使用循环遍历数组,逐个元素进行判断。如果找到了'SUB-SECURITY' 和 'SUB-OPERATOR',则返回 True,否则返回 False。
def check_exist(arr): sub_security_found = False sub_operator_found = False for element in arr: if element == 'SUB-SECURITY': sub_security_found = True if element == 'SUB-OPERATOR': sub_operator_found = True return sub_security_found and sub_operator_found # 示例用法 arr = ['SUB-SECURITY', 'SUB-OPERATOR', 'OTHER-ELEMENT'] result = check_exist(arr) print(result) # 输出:True -
使用集合 (Set):
将数组转换为集合,然后通过判断集合中是否包含'SUB-SECURITY' 和 'SUB-OPERATOR' 来确定是否存在。
def check_exist(arr): element_set = set(arr) return 'SUB-SECURITY' in element_set and 'SUB-OPERATOR' in element_set # 示例用法 arr = ['SUB-SECURITY', 'SUB-OPERATOR', 'OTHER-ELEMENT'] result = check_exist(arr) print(result) # 输出:True
以上两种方法都可以判断数组中是否存在'SUB-SECURITY' 和 'SUB-OPERATOR',可以根据具体情况选择使用。
原文地址: https://www.cveoy.top/t/topic/nAM4 著作权归作者所有。请勿转载和采集!