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

如何在Python字典中为每个键存储x、y坐标数组?

Fixing Dictionary Coordinate Storage to Save [X,Y] Pairs

Hey there! Let's sort out this issue. The problem with your current code is that you're overwriting the value of p[i] twice—first with the X coordinate, then right away with the Y coordinate. That's why only the Y value ends up stored for each key.

Here's the fixed code that will store each [X,Y] pair as a list in your dictionary:

p = {} 
for i in range(4): 
    while True: 
        p_input = input("Enter starting point X,Y Coordinates:") 
        p_components = p_input.split(',') 
        if len(p_components) != 2: 
            print("Missing coordinate please try again.") 
        else:
            # Convert both values to floats and store as a single list
            x = float(p_components[0].strip())
            y = float(p_components[1].strip())
            p[i] = [x, y]
            break 
print(p) 

Key Fixes & Improvements:

  • Instead of assigning p[i] twice, we create a list containing both converted X and Y values and assign that list to p[i]. This ensures both coordinates are stored together.
  • Added .strip() to handle extra spaces around the comma (like if someone inputs 2 , 5)—this makes the input handling more robust and avoids errors from unexpected whitespace.
  • Fixed a small input bug: in your original code, if the first input was invalid, the second input request wasn't processed properly. Now all input attempts are handled within the while loop correctly.

After running this, your dictionary p will be formatted exactly as you want: {0:[x1,y1], 1:[x2,y2], 2:[x3,y3], 3:[x4,y4]}.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:18:19