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

如何基于用户输入的牛群规模创建含自定义键名的字典

Got it, let's sort this out for you! First, we'll fix the input bug in your original code, then adjust it to build the dictionary you need. Here's a step-by-step solution:

Solution: Create a Dictionary of Cow IDs

Your goal is to build a dictionary where each key is a custom cow ID tag, and we can pair each key with relevant data (like milk yield, since your original code mentions yield entry). Let's break this down:

  1. Fix the input mistake: Your original code incorrectly tried to pass a string directly to int()—we need to use input() to capture user input first, then convert it to an integer.
  2. Use a dictionary instead of a list: Initialize an empty dictionary, then populate it with each cow's ID as the key.
  3. Optional: Add yield data: Since your code mentions "initiating yield entry", we can extend the solution to collect yield values right away or set a placeholder for later.

Corrected Code Example

# Initialize empty dictionary to store cow IDs and their data
cow_dict = {}

# Get herd size from user input
herd_size = int(input("Enter the size of the herd: "))

for cow_num in range(herd_size):
    # Get valid 3-digit ID from user (fixed input statement)
    cow_id = int(input(f"Enter a unique 3-digit ID tag for cow {cow_num + 1}: "))
    # Add ID as a key to the dictionary; set placeholder value (replace with yield input if needed)
    cow_dict[cow_id] = None

print("Initiating yield entry...")
# Optional: Collect milk yield data for each cow
for cow_id in cow_dict:
    yield_amount = float(input(f"Enter milk yield (in liters) for cow {cow_id}: "))
    cow_dict[cow_id] = yield_amount

# Verify the final dictionary
print("\nFinal cow yield data:", cow_dict)

Useful Additions (Optional)

To make the code more robust, you can add checks for valid/unique IDs:

  • Enforce 3-digit IDs:
    while True:
        cow_id_input = input(f"Enter a unique 3-digit ID tag for cow {cow_num + 1}: ")
        if len(cow_id_input) == 3 and cow_id_input.isdigit():
            cow_id = int(cow_id_input)
            break
        print("Oops! Please enter a valid 3-digit number.")
    
  • Prevent duplicate IDs:
    while cow_id in cow_dict:
        print("That ID is already in use! Please enter a unique one.")
        cow_id = int(input(f"Enter a unique 3-digit ID tag for cow {cow_num + 1}: "))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:00:15