如何在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 top[i]. This ensures both coordinates are stored together. - Added
.strip()to handle extra spaces around the comma (like if someone inputs2 , 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
相关产品推荐
相关产品推荐

