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

Python编程作业:商品库存列表输出格式修正求助

Fixing Your Python Inventory Formatting Issue

Hey there! Let's get that inventory list outputting correctly. The problem with your current code is that it's just slicing the first 7 characters of each input string instead of properly splitting the product name and quantity, plus converting the quantity to an integer.

Here's the Corrected Code

def process_input(lst):
    # Split each entry into name and quantity, convert quantity to integer
    result = [[item.split()[0], int(item.split()[1])] for item in lst]
    return result

string = input()
lines = []
while string != "END":
    lines.append(string)
    string = input()
print(process_input(lines))

What Changed & Why

  • Splitting the string: Using split() on each input string breaks it into a list of two elements (e.g., "Choc 5" becomes ["Choc", "5"]). This works even if there's a tab or extra space instead of a regular space, since split() with no arguments handles any whitespace.
  • Converting quantity to integer: Wrapping item.split()[1] with int() turns the string quantity into a numeric integer, which matches your desired output format.
  • Optional map+lambda version: If you prefer using map instead of list comprehensions, this equivalent code works too:
    result = list(map(lambda x: [x.split()[0], int(x.split()[1])], lst))
    

Testing It Out

If your input lines are:

Choc 5
Vani 10
Stra 7
Choc 3
Stra 4
END

The output will be exactly what you're looking for:
[['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:44:38