3. Python基础快速回顾(一):变量与数据类型、字符串操作、列表与字典、条件判断与循环结构

在进入额度模型评分沙盘开发之前,我们需要快速巩固Python最核心的基础知识。本章将围绕四个关键模块展开:变量与数据类型、字符串操作、列表与字典、条件判断与循环结构。这些内容将直接应用于后续的评分卡数据处理、特征工程和模型逻辑实现中。

3.1 变量与数据类型

Python是动态类型语言,变量不需要提前声明类型,赋值时自动推断。理解基本数据类型是构建一切逻辑的基石。

数据类型 示例 说明
int(整数) age = 30 无小数部分,用于计数、索引
float(浮点数) score = 0.85 带小数,用于评分、概率
str(字符串) name = "张三" 文本数据,用于客户姓名、标签
bool(布尔值) is_default = False 仅 True/False,用于条件判断
NoneType(空值) missing = None 表示缺失或未定义
额度模型提示:在评分沙盘中,float 用于存储概率值和分数,int 用于客户ID和年龄,str 用于处理特征名称和标签映射。None 常用于标记缺失值,后续需要做填充处理。
# 变量赋值与类型查看
customer_id = 1001
credit_score = 0.72
customer_name = "李四"
is_approved = True

print(type(customer_id))   # <class 'int'>
print(type(credit_score))  # <class 'float'>
print(type(customer_name)) # <class 'str'>
print(type(is_approved))   # <class 'bool'>

3.2 字符串操作

字符串在数据清洗和特征工程中频繁使用。Python提供了丰富的字符串方法,用于格式化、分割、替换和判断。

常用字符串方法

方法 作用 示例 结果
.strip() 去除首尾空白 " 张三 ".strip() "张三"
.split() 按分隔符拆分 "a,b,c".split(",") ["a","b","c"]
.replace() 替换子串 "2023-01".replace("-","/") "2023/01"
.upper() 转大写 "score".upper() "SCORE"
.startswith() 判断前缀 "APP_001".startswith("APP") True
# 字符串操作实战
raw_text = "  客户ID: CUST_1024, 评分: 0.68  "
cleaned = raw_text.strip()
parts = cleaned.split(",")
id_part = parts[0].replace("客户ID: ", "")
score_part = parts[1].replace("评分: ", "")

print(f"提取ID: {id_part}")    # 提取ID: CUST_1024
print(f"提取评分: {score_part}") # 提取评分: 0.68
格式化字符串:推荐使用 f-string(Python 3.6+),语法简洁且性能好。f"客户 {name} 的信用分为 {score}" 比 .format() 和 % 更直观。

3.3 列表与字典

列表和字典是Python中最常用的两种容器类型。列表用于有序集合,字典用于键值对映射。在评分沙盘中,列表存储特征向量,字典存储客户属性。

列表操作

操作 代码 结果
创建 scores = [0.6, 0.8, 0.75] [0.6, 0.8, 0.75]
索引 scores[1] 0.8
切片 scores[0:2] [0.6, 0.8]
追加 scores.append(0.9) [0.6, 0.8, 0.75, 0.9]
排序 sorted(scores, reverse=True) [0.9, 0.8, 0.75, 0.6]

字典操作

操作 代码 结果
创建 cust = {"id":1001, "score":0.72} {'id':1001, 'score':0.72}
取值 cust.get("score") 0.72
修改 cust["score"] = 0.85 {'id':1001, 'score':0.85}
遍历键 for k in cust: print(k) id score
遍历键值 for k,v in cust.items(): print(k,v) id 1001 score 0.85
# 列表与字典综合应用
feature_names = ["年龄", "收入", "负债比", "信用历史"]
feature_values = [35, 15000, 0.42, 0.88]

# 构建特征字典
feature_dict = {}
for i in range(len(feature_names)):
    feature_dict[feature_names[i]] = feature_values[i]

print(feature_dict)
# {'年龄': 35, '收入': 15000, '负债比': 0.42, '信用历史': 0.88}

# 列表推导式快速筛选
high_scores = [v for v in feature_values if v > 0.5]
print(high_scores)  # [15000, 0.88]
常见错误:字典的键必须是不可变类型(字符串、数字、元组)。不要使用列表作为字典键,否则会引发 TypeError: unhashable type: 'list'。

3.4 条件判断与循环结构

条件判断和循环是控制程序流程的核心。在评分沙盘中,条件判断用于规则过滤和分箱逻辑,循环用于批量处理客户数据。

条件判断:if-elif-else

# 评分等级划分
score = 0.72

if score >= 0.8:
    level = "优质"
elif score >= 0.6:
    level = "标准"
elif score >= 0.4:
    level = "关注"
else:
    level = "拒绝"

print(f"评分 {score} 对应等级: {level}")
# 评分 0.72 对应等级: 标准

循环结构:for 和 while

循环类型 适用场景 示例
for 遍历已知序列(列表、字典、字符串) for score in scores: print(score)
while 条件控制,未知迭代次数 while count < 10: count += 1
break 提前退出循环 if score < 0.3: break
continue 跳过当前迭代 if score is None: continue
# 批量处理客户评分
customers = [
    {"id": 1001, "score": 0.85},
    {"id": 1002, "score": 0.45},
    {"id": 1003, "score": 0.92},
    {"id": 1004, "score": 0.33},
]

approved_list = []
for cust in customers:
    if cust["score"] >= 0.6:
        approved_list.append(cust["id"])
        print(f"客户 {cust['id']} 通过审批")
    else:
        print(f"客户 {cust['id']} 未通过")

print(f"通过审批的客户ID列表: {approved_list}")
循环优化建议:在评分沙盘中处理大量客户数据时,优先使用 for 循环配合列表推导式或 map() 函数,避免显式 while 循环带来的无限循环风险。使用 enumerate() 可以同时获取索引和值。
Python基础结构在评分沙盘中的应用流程 原始客户数据 字符串清洗 + 列表/字典存储 .strip() .split() 列表推导式 字典映射 条件判断:规则过滤 if score >= 0.6: 通过 else: 拒绝 循环结构:批量评分计算 for cust in customers: 计算评分 评分结果输出

3.5 综合案例:客户评分快速处理

将本节知识点串联,实现一个简单的客户评分处理脚本。该脚本读取原始数据,清洗字符串,存储为字典,进行条件判断,并通过循环批量输出结果。

# 模拟原始数据(字符串格式)
raw_data = [
    "客户ID: C001, 年龄: 32, 收入: 18000, 负债比: 0.35",
    "客户ID: C002, 年龄: 45, 收入: 25000, 负债比: 0.50",
    "客户ID: C003, 年龄: 28, 收入: 12000, 负债比: 0.65",
]

# 清洗并转换为字典列表
customers = []
for line in raw_data:
    # 去除首尾空格,按逗号分割
    parts = line.strip().split(",")
    cust_dict = {}
    for part in parts:
        key, value = part.split(":")
        key = key.strip()
        value = value.strip()
        # 根据键名转换数据类型
        if key == "客户ID":
            cust_dict["id"] = value
        elif key == "年龄":
            cust_dict["age"] = int(value)
        elif key == "收入":
            cust_dict["income"] = float(value)
        elif key == "负债比":
            cust_dict["debt_ratio"] = float(value)
    customers.append(cust_dict)

# 条件判断:计算简单评分(示例规则)
def calculate_score(cust):
    base = 0.5
    if cust["age"] <= 35:
        base += 0.1
    if cust["income"] > 15000:
        base += 0.2
    if cust["debt_ratio"] < 0.4:
        base += 0.2
    elif cust["debt_ratio"] < 0.6:
        base += 0.1
    else:
        base -= 0.1
    return round(min(max(base, 0.0), 1.0), 2)

# 循环批量处理
print("客户评分结果:")
for cust in customers:
    score = calculate_score(cust)
    cust["score"] = score
    if score >= 0.7:
        level = "优质"
    elif score >= 0.5:
        level = "标准"
    else:
        level = "关注"
    print(f"{cust['id']}: 评分 {score} → {level}")
运行结果预览:
客户ID: C001: 评分 0.8 → 优质
客户ID: C002: 评分 0.7 → 优质
客户ID: C003: 评分 0.5 → 标准

通过这个案例,可以看到变量、字符串、列表、字典、条件判断和循环是如何协同工作的。在后续的额度模型评分沙盘开发中,这些基础操作将反复出现,成为构建复杂评分引擎的基石。