我要求完成的代码的目的是接收给定库存的输入,将它们返回到一行中的列表中。然后在第二行,复制列表,但这次加倍数字。
给定的输入是
Choc 5; Vani 10; Stra 7; Choc 3; Stra 4
所需的输出是:
[['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]]
[['Choc', 10], ['Vani', 20], ['Stra', 14], ['Choc', 6], ['Stra, 8]]
我成功地为第一线获得了所需的输出,但我正在努力争取如何成功地与第二线竞争。
这是代码:
def process_input(lst):
result = []
for string in lines:
res = string.split()
result.append([res[0], int(res[1])])
return result
def duplicate_inventory(invent):
# your code here
return = []
return result
# DON’T modify the code below
string = input()
lines = []
while string != "END":
lines.append(string)
string = input()
inventory1 = process_input(lines)
inventory2 = duplicate_inventory(inventory1)
print(inventory1)
print(inventory2)
答案 0 :(得分:9)
由于你已经完成了第一行,你可以使用一个简单的列表理解来获得第二行:
x = [[i, j*2] for i,j in x]
print(x)
输出:
[['Choc', 10], ['Vani', 20], ['Stra', 14], ['Choc', 6], ['Stra', 8]]
答案 1 :(得分:0)
如果您希望避免使用显式循环,以下是常用的单行代码:
x = 'Choc 5; Vani 10; Stra 7; Choc 3; Stra 4'
res1 = [[int(j) if j.isdigit() else j for j in i.split()] for i in x.split(';')]
res2 = [[int(j)*2 if j.isdigit() else j for j in i.split()] for i in x.split(';')]
print(res1)
print(res2)
# [['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]]
# [['Choc', 10], ['Vani', 20], ['Stra', 14], ['Choc', 6], ['Stra', 8]]
答案 2 :(得分:0)
另一种方法
((SolidBrush)color).Color.Name