Python编程新手求助:修复parse_list函数实现输入转目标二维列表
Fixing Your
parse_list Function Hey there! Let's walk through fixing your code so it works exactly like you want it to. I spotted three key issues in your original code that are causing it to fail:
Key Issues in Your Original Code
- Empty list index error: You initialized
xy = []as an empty list, then tried to assign values toxy[i][0]andxy[i][1]directly. Sincexyhas no elements yet,xy[i]doesn't exist—this will throw anIndexErrorevery time. - No string-to-integer conversion: When you split the input strings, you get string values like
"1"instead of integers. Your desired output uses integers, so we need to convert these. - No return value or output: Your function doesn't return the
xylist, and you don't print the result after calling it—even if the function worked, you'd never see the output.
Corrected Code
Here's the fixed version with explanations:
def parse_list(str_x, str_y): # Split input strings and convert each element to integer in one step list_x = [int(num) for num in str_x.split(',')] list_y = [int(num) for num in str_y.split(',')] xy = [] # Pair elements directly using zip() for cleaner code for x, y in zip(list_x, list_y): xy.append([x, y]) # Return the final paired list return xy str_x = input('x: ') str_y = input('y: ') # Capture the result and print it result = parse_list(str_x, str_y) print('xy:', result)
Quick Notes on Improvements:
- Used list comprehensions to split and convert input strings to integers in a clean, concise way.
- Switched to
zip(list_x, list_y)to pair elements directly—this is more readable than usingrange(len(list_x))and handles element pairing naturally. - Added a
returnstatement to pass the finished paired list back from the function. - Captured the function's output and printed it so you can see the result clearly.
Testing It Out
If you input:
x: 1,2,3 y: 4,5,6
You'll get the exact output you want:
xy: [[1,4],[2,5],[3,6]]
内容的提问来源于stack exchange,提问作者yammayamm
相关产品推荐
相关产品推荐

