在 Python 中,要判断一个字符串是否在一个字符串数组中,即使数组包含字典,也可以通过以下步骤完成:

  1. 遍历字符串数组中的每个元素。
  2. 检查每个元素是否为字典类型。
  3. 如果是字典类型,使用字典的键或值来判断字符串是否存在于字典中。
  4. 如果找到了匹配的字符串,返回 True。
  5. 如果遍历完数组后都没有找到匹配的字符串,返回 False。

以下是一个示例代码:

def check_string_in_array(string, array):
    for element in array:
        if isinstance(element, dict):
            if string in element.keys() or string in element.values():
                return True
    return False

使用示例:

array = [{'name': 'John', 'age': 25}, {'name': 'Alice', 'age': 30}]
string = 'John'

if check_string_in_array(string, array):
    print('字符串存在于数组中')
else:
    print('字符串不存在于数组中')

在上述示例中,检查字符串'John'是否在数组array中。由于'John'是字典中的一个值,所以返回结果为'字符串存在于数组中'。

Python: 如何判断一个字符串是否在一个包含字典的字符串数组中

原文地址: https://www.cveoy.top/t/topic/P2D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录