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

如何在Python+Jupyter Notebook中实现循环列表并每次移除用户输入元素,直至选出获胜三元组

Fixing Your Tic-Tac-Toe Style Selection Loop

Hey there! Let's get this loop working for you—since you're new to Python and Jupyter, I'll keep this clear and walk through each part step by step.

First, let's fix the small issues in your initial code, then build out the full loop logic that keeps going until the user picks a winning trio.

Key Requirements We Need to Cover

  • Only accept inputs like x1 to x9
  • Don't let the user pick the same element twice
  • Keep asking for inputs until the 3 selected elements match one of your winning sets
  • Give clear feedback for valid/invalid inputs

Full Working Code (With Comments)

# Define all winning combinations
all_wins = (('x1','x2','x3'), ('x4','x5','x6'), ('x7','x8','x9'),
            ('x1','x4','x7'), ('x2','x5','x8'), ('x3','x6','x9'),
            ('x1','x5','x9'), ('x7','x5','x3'))

# Create a set of all valid items (easy to remove items as they're selected)
valid_items = {'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9'}

# Track the user's selected items
selected = []

# Loop until we have a winning trio
while True:
    # Check if the current selected items form a winning combination
    if len(selected) >= 3:
        selected_set = set(selected)
        # Check if any winning set is entirely contained in selected items
        for win in all_wins:
            if set(win).issubset(selected_set):
                print(f"Congratulations! You won with {selected}!")
                # Exit the loop since we found a winner
                break
        else:
            # If no win was found, keep the loop going
            pass
        else:
            # This runs only if we broke out of the for loop (found a win)
            break
    
    # Get user input, strip extra whitespace just in case
    user_input = input("Please enter x followed by a number 1-9: ").strip()
    
    # Validate the input
    if user_input in valid_items:
        # Add to selected list and remove from valid options
        selected.append(user_input)
        valid_items.remove(user_input)
        print(f"Good choice! Selected so far: {selected}")
    else:
        # Give specific feedback for invalid inputs
        if user_input in selected:
            print("You already picked that one! Try another.")
        else:
            print("That's not a valid input. Use format like x1, x2, ..., x9.")

Let's Break Down What This Does

  1. Valid Items Set: Using a set for valid_items makes it super easy to remove items once they're selected—no messy manual duplicate checks (though we still give clear feedback if the user tries to re-pick).
  2. Infinite Loop with Exit Condition: The while True loop runs forever until we hit the winning condition, where we break out of the loop.
  3. Win Check: Once the user has 3 or more items, we convert their selections to a set and use issubset() to check if any winning trio is fully contained in their picks—this is a clean, Pythonic way to compare groups.
  4. Input Validation: We check if the input is in our valid set. If yes, we update our tracking lists; if not, we tell the user exactly what went wrong (duplicate vs. invalid format).

Testing This in Jupyter

Just copy this code into a Jupyter cell and run it—you'll see the prompts right in the notebook, and it will keep going until you pick a winning trio (like x1, x2, x3 or x1, x5, x9).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:52:39