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, sincesplit()with no arguments handles any whitespace. - Converting quantity to integer: Wrapping
item.split()[1]withint()turns the string quantity into a numeric integer, which matches your desired output format. - Optional map+lambda version: If you prefer using
mapinstead 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
相关产品推荐
相关产品推荐

