You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python提取int变量名存入列表失败及变量替换问题求助

问题分析与修复方案

第一个问题:提取int变量名失败

原代码存在两处核心错误:

  • 错误地将data列表转为字符串后遍历单个字符,而非遍历列表中的每一行代码
  • 判断逻辑不匹配实际场景:startswith("int")无法匹配行中间的int声明,endswith(list_end)也不符合变量名的提取逻辑

修复后的提取代码:

list_end = {"=", ";", ")", "(", " ", "="}
list_variable = []

data = ["int z;",
"public data_type getCurrentSteps() {int z = true;if (getType() != 1) {z = false;",
"public final class a extends b implements Leaderboard {public final int nu;public a(d dVar, data_type i, data_type i2) {super(dVar, i);this.nu = i2;",
"public int getScoreOrder() {return getInteger;",
"arrayList = new ArrayList<>(this.nu);for (int i = 0; i < this.nu; i++)",
"public final class a extends b implements Achievement {public a(d dVar, int i) {super(dVar, i);",
"public int getCurrentSteps() {int z = true;if (getType() != 1) {z = false;",
"public String getFormattedCurrentSteps() {int z = true;if (getType() != 1) {z = false;",
"public int getTotalSteps() {int z = true;if (getType() != 1) {z = false;",
"public int getType() {return getInteger();",
"public class a {public static void a(GoogleMapOptions googleMapOptions, Parcel parcel, int i) {data_type k = b.k(parcel);"]

# 遍历每一行代码
for line in data:
    index = 0
    while True:
        # 定位当前行中"int "的位置
        int_pos = line.find("int ", index)
        if int_pos == -1:
            break
        # 跳过"int ",定位到变量名起始点
        var_start = int_pos + 4
        var_end = var_start
        # 向后遍历直到遇到终止符号,确定变量名边界
        while var_end < len(line) and line[var_end] not in list_end:
            var_end += 1
        # 提取变量名,去重后加入列表
        var_name = line[var_start:var_end].strip()
        if var_name and var_name not in list_variable:
            list_variable.append(var_name)
        # 更新索引,避免重复处理同一行的int声明
        index = var_end

print(list_variable)  # 输出: ['z', 'nu', 'i']

第二个问题:变量替换无效

原代码存在两处核心错误:

  • 替换时误用字符串"b"而非变量b
  • 字符串是不可变类型,replace()不会修改原字符串,需重新赋值或存入新列表

修复后的替换代码:

# 创建新列表存储替换后的结果
modified_data = []
for line in data:
    modified_line = line
    for var in list_variable:
        # 用变量var而非字符串"b"进行替换
        modified_line = modified_line.replace(var, "variable")
    modified_data.append(modified_line)

# 查看替换后的结果
for line in modified_data:
    print(line)

内容的提问来源于stack exchange,提问作者ya xi er

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 00:55:14