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

如何实现用户对商品数组的编辑功能及相关数组操作需求

Got it, let's break down how to build this product management system with all the features you need. I'll use Python since it's intuitive and widely used for such tasks.

Product Management System Implementation

Step 1: Initialize Product Data Arrays

First, we'll create three separate arrays to store product IDs, prices, and inventory counts. I'll start with sample data, but you can replace these with your own values.

# Initialize arrays for product data (5 entries each)
product_ids = ["P001", "P002", "P003", "P004", "P005"]
product_prices = [19.99, 29.99, 9.99, 49.99, 39.99]
product_inventories = [50, 30, 100, 20, 75]

Step 2: Print All Product Data

This function will format and display all product information in a clean, readable table.

def print_all_products():
    print("\n=== Current Product Data ===")
    # Header row with aligned columns
    print(f"{'Product ID':<8} {'Price':<8} {'Inventory':<10}")
    print("-----------------------------")
    # Loop through each product to print details
    for idx in range(len(product_ids)):
        print(f"{product_ids[idx]:<8} ${product_prices[idx]:<7.2f} {product_inventories[idx]:<10}")

Step 3: Edit Product Data (Core Feature)

This function handles user input to edit any product's ID, price, or inventory. It includes error handling to prevent invalid inputs and crashes.

def edit_product():
    # Get valid product index (user-friendly 1-based numbering)
    while True:
        try:
            product_num = int(input("\nEnter the product number (1-5) you want to edit: "))
            idx = product_num - 1  # Convert to 0-based array index
            if idx < 0 or idx >= 5:
                print("Oops! Product number must be between 1 and 5.")
                continue
            break
        except ValueError:
            print("Please enter a valid number for the product.")
    
    # Get valid field to edit
    while True:
        field = input("Which field do you want to edit? (id/price/inventory): ").lower()
        if field not in ["id", "price", "inventory"]:
            print("Invalid field! Choose 'id', 'price', or 'inventory'.")
            continue
        break
    
    # Update the selected field with validation
    if field == "id":
        new_id = input(f"Enter new ID for Product {product_num}: ")
        product_ids[idx] = new_id
    elif field == "price":
        while True:
            try:
                new_price = float(input(f"Enter new price for Product {product_num}: $"))
                if new_price < 0:
                    print("Price can't be negative!")
                    continue
                product_prices[idx] = new_price
                break
            except ValueError:
                print("Please enter a valid number for price.")
    elif field == "inventory":
        while True:
            try:
                new_inv = int(input(f"Enter new inventory count for Product {product_num}: "))
                if new_inv < 0:
                    print("Inventory can't be negative!")
                    continue
                product_inventories[idx] = new_inv
                break
            except ValueError:
                print("Please enter a valid whole number for inventory.")
    
    # Show updated data right after editing
    print("\n✅ Product updated successfully! Here's the latest data:")
    print_all_products()

Step 4: Main Workflow

This ties everything together: initial data display, repeated editing options, and final data summary.

def main():
    # Show initial product data
    print("Welcome to the Product Manager!")
    print_all_products()
    
    # Allow user to edit multiple times
    while True:
        choice = input("\nDo you want to edit a product? (yes/no): ").lower()
        if choice == "yes":
            edit_product()
        elif choice == "no":
            break
        else:
            print("Please enter 'yes' or 'no'.")
    
    # Print final, updated data
    print("\n=== Final Product Data Summary ===")
    print_all_products()
    print("Thanks for using the Product Manager!")

# Run the program
if __name__ == "__main__":
    main()

Key Features of This Implementation

  • User-Friendly Input: Uses 1-based numbering for products (since users don't think in 0-based indices)
  • Error Handling: Prevents crashes from invalid inputs (non-numbers, out-of-range indices, negative values)
  • Instant Feedback: Shows updated data immediately after each edit
  • Flexible Editing: Lets users edit any field of any product as many times as needed

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:21:17