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

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 to xy[i][0] and xy[i][1] directly. Since xy has no elements yet, xy[i] doesn't exist—this will throw an IndexError every 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 xy list, 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 using range(len(list_x)) and handles element pairing naturally.
  • Added a return statement 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:33:21