Python3中向字典指定键的元组列表追加元组失败问题
问题分析与解决方案
我明白你现在的困扰——明明第一个append成功了,第二个却没生效,其实问题出在字符串大小写不匹配导致的条件判断失败,同时咱们还可以优化代码结构,方便后续遍历多文件的需求。
为什么第二个append没生效?
看你第三个if的判断条件:
if (c[0].strip()).lower() == "@@Max_connections" and int(c[1].lstrip())<152:
这里(c[0].strip()).lower()会把"@@Max_connections"转换成全小写的"@@max_connections",但你右边写的是混合大小写的"@@Max_connections",两者不相等,所以这个if条件永远为False,自然不会执行append操作。
修复后的代码
把第三个if的条件右边改成全小写,同时我们可以优化代码结构,避免重复的split、strip操作,让后续扩展更方便:
x = " @@Hostname: host1" y = "@@innodb_buffer_pool_size: 1" z = " @@Max_connections: 150" op = {} # 把所有配置项放到列表里,方便循环处理 config_items = [x, y, z] host = "" for item in config_items: # 只按第一个冒号分割,避免值里包含冒号的异常情况 key_part, value_part = item.split(':', 1) clean_key = key_part.strip() clean_value = value_part.strip() lower_key = clean_key.lower() # 处理主机名逻辑 if lower_key == "@@hostname": host = clean_value if host not in op: op[host] = [] # 处理innodb缓冲池配置 elif lower_key == "@@innodb_buffer_pool_size": if int(clean_value) < 2: op[host].append((clean_key.lstrip('@@'), clean_value)) # 处理最大连接数配置(修正大小写匹配问题) elif lower_key == "@@max_connections": if int(clean_value) < 152: op[host].append((clean_key.lstrip('@@'), clean_value)) print(op)
运行这段代码就能得到你期望的输出:
{'host1': [('innodb_buffer_pool_size', '1'), ('Max_connections', '150')]}
如果希望max_connections是全小写的键,可以把clean_key.lstrip('@@')改成clean_key.lstrip('@@').lower()。
后续扩展建议
因为你后续要遍历多文件,建议把配置行的处理逻辑封装成函数,让代码更易维护:
def process_config_line(line, op, current_host): if not line.strip(): return current_host try: key_part, value_part = line.split(':', 1) except ValueError: # 跳过格式不正确的行 return current_host clean_key = key_part.strip() clean_value = value_part.strip() lower_key = clean_key.lower() if lower_key == "@@hostname": new_host = clean_value if new_host not in op: op[new_host] = [] return new_host elif current_host: # 仅当已获取到主机名时,处理配置项 if lower_key == "@@innodb_buffer_pool_size" and int(clean_value) < 2: op[current_host].append((clean_key.lstrip('@@').lower(), clean_value)) elif lower_key == "@@max_connections" and int(clean_value) < 152: op[current_host].append((clean_key.lstrip('@@').lower(), clean_value)) return current_host # 遍历文件的示例代码 op = {} current_host = "" with open('mysql_config.txt', 'r') as f: for line in f: current_host = process_config_line(line, op, current_host)
这样处理多文件时逻辑更清晰,也更容易添加新的配置项判断。
内容的提问来源于stack exchange,提问作者udhayan dharmalingam
相关产品推荐
相关产品推荐

