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

如何向嵌套数组添加元素并完善Python库存录入脚本

问题:修改Python脚本实现批量设备信息录入

需要实现的功能:

  • 从预设选项选择设备类型(equipment_type)
  • 从预设选项选择设备型号(equipment_model)
  • 选择设备是否租赁(True/False)
  • 批量扫描设备序列号,无需重复运行脚本

最终输出格式示例:

['CNX000000000952708', 'Laptop', 'Dell XP1', True]
['CNX000000000952705', 'Laptop', 'Dell XP1', True]

修改后的完整代码

# 设备类型选项映射
type_options = {
    "1": "Desktop",
    "2": "Dock Monitor",
    "3": "Docking Station",
    "4": "Laptop",
    "5": "Monitor",
    "6": "Printer",
    "7": "Projector",
    "8": "Scanner",
    "9": "Surface Keyboard",
    "10": "Surface Pen",
    "11": "Tablet",
    "12": "Tiny-in-One Monitor"
}

# 设备型号选项映射
model_options = {
    "1": "P15s Gen1",
    "2": "P15s Gen2",
    "3": "P53s",
    "4": "Surface Pro 7",
    "5": "Thinkbook 15 G2",
    "6": "Thinkcentre M75Q",
    "7": "Thinkvision P24h-20",
    "8": "Thinkvision T2454p",
    "9": "Thinkvision T24i-20"
}

# 选择设备类型
print("Select Equipment Type")
for key, value in type_options.items():
    print(f"{key}: {value}")
while True:
    equipment_type_input = input("Enter your choice (1-12): ")
    if equipment_type_input in type_options:
        equipment_type = type_options[equipment_type_input]
        break
    print("Invalid choice, please enter a number between 1 and 12")

# 选择设备型号
print("\nSelect Equipment Model")
for key, value in model_options.items():
    print(f"{key}: {value}")
while True:
    equipment_model_input = input("Enter your choice (1-9): ")
    if equipment_model_input in model_options:
        equipment_model = model_options[equipment_model_input]
        break
    print("Invalid choice, please enter a number between 1 and 9")

# 确认租赁状态
print("\n----")
while True:
    lease_input = input("Is this a lease? Y/N: ").strip().upper()
    if lease_input in ["Y", "N"]:
        lease = lease_input == "Y"
        break
    print("Invalid input, please enter Y or N")

# 批量扫描序列号
serial_numbers = []
print("\nStart scanning serial numbers (enter 'done' when finished):")
while True:
    s = input("Scan Serial Number: ").strip()
    if s.lower() == "done":
        break
    if s:  # 跳过空输入
        serial_numbers.append(s)

# 构建最终库存数组
inventory = [[serial, equipment_type, equipment_model, lease] for serial in serial_numbers]

# 输出结果
print("\nFinal Inventory:")
for item in inventory:
    print(item)

核心修改说明

  1. 调整流程顺序:先收集所有设备通用信息(类型、型号、租赁状态),再扫描序列号,确保所有序列号都能复用这些信息,满足批量录入需求
  2. 用字典简化选项映射:替代原代码中冗长的if-elif链,后续新增或修改选项只需更新字典,代码更易维护
  3. 添加输入验证:通过循环确保用户输入有效的选项,避免无效值导致程序异常
  4. 直接构建目标数组:使用列表推导式一次性将序列号与设备信息组合成子数组,无需先创建单元素数组再追加内容
  5. 过滤空输入:扫描序列号时自动跳过空值,避免无效数据进入库存列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:50:35