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

Python创建关联GroupID与描述的可选多选列表求助

解决方案

1. 读取并整理分组数据

先优化文件读取逻辑,把GroupID和对应描述一一配对,避免单独存储列表的混乱:

# 读取文件并清理换行符、空行
with open("cgIDmod2.txt", "r") as f:
    # 过滤空行并去除每行首尾空白字符(包括换行符)
    cleaned_lines = [line.strip() for line in f if line.strip()]

# 将奇数行的GroupID与偶数行的描述配对
# cleaned_lines[::2] 取索引0、2、4...的行(对应GroupID)
# cleaned_lines[1::2] 取索引1、3、5...的行(对应描述)
group_mapping = list(zip(cleaned_lines[::2], cleaned_lines[1::2]))

2. 实现多选菜单交互

制作仅显示描述的菜单,支持用户多选序号,后台自动关联对应GroupID:

# 显示分组选择菜单
print("=== 分组选择菜单 ===")
for idx, (group_id, desc) in enumerate(group_mapping, start=1):
    print(f"{idx}. {desc}")

# 获取并解析用户输入
user_input = input("\n请输入选择的序号(多个用逗号分隔,范围用-,例如1,3-5):").strip()
selected_indices = []

# 解析输入的每一段内容
for segment in user_input.split(","):
    segment = segment.strip()
    if not segment:
        continue
    # 处理范围输入(如1-3)
    if "-" in segment:
        try:
            start, end = map(int, segment.split("-"))
            # 转换为列表索引(从0开始)
            selected_indices.extend(range(start-1, end))
        except ValueError:
            print(f"无效输入:{segment},已跳过")
    # 处理单个序号输入
    else:
        try:
            idx = int(segment) - 1
            if 0 <= idx < len(group_mapping):
                selected_indices.append(idx)
            else:
                print(f"序号{segment}超出范围,已跳过")
        except ValueError:
            print(f"无效输入:{segment},已跳过")

# 去重并筛选有效索引
unique_indices = list(set(selected_indices))
valid_indices = [i for i in unique_indices if 0 <= i < len(group_mapping)]

# 获取最终选中的GroupID
selected_group_ids = [group_mapping[i][0] for i in valid_indices]

print("\n选中的GroupID:")
for gid in selected_group_ids:
    print(gid)

3. 传递GroupID到后续API

拿到selected_group_ids后,即可直接传递给下一个API任务,示例如下:

import requests

# 后续API的地址
next_api_url = "https://test123.com/your-next-endpoint"

# 假设API接受JSON格式的GroupID列表,可按需调整请求方式/参数
response = requests.post(
    next_api_url,
    json={"selected_group_ids": selected_group_ids},
    # 如果需要登录态,可带上之前登录获取的cookies或token
    # cookies=your_login_cookies,
    # headers={"Authorization": f"Bearer {your_token}"}
)

# 处理API响应
if response.status_code == 200:
    print("API请求成功")
else:
    print(f"API请求失败,状态码:{response.status_code}")

关键说明

  • 用with语句操作文件,无需手动关闭,更安全可靠。
  • 清理文件行时过滤空行,避免因文件格式问题导致配对错误。
  • 菜单支持多种输入格式,同时对无效输入做了异常处理,避免程序崩溃。

内容的提问来源于stack exchange,提问作者Clems R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:27:17