Python3将列表中的数字乘以

2024-05-15 13:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我被要求完成的代码的目的是接收给定库存的输入,并在一行中以列表的形式返回它们。然后在第二行,复制列表,但这次是双倍的数字。你知道吗

给定的输入是

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)

Tags: 代码列表inputstringreturndefresresult
2条回答

如果您希望避免显式循环,以下是常见的一行程序:

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]]

由于您已经完成了第一行,因此可以使用简单的列表理解来获得第二行:

x = [[i, j*2] for i,j in x]
print(x)

输出:

[['Choc', 10], ['Vani', 20], ['Stra', 14], ['Choc', 6], ['Stra', 8]]

相关问题 更多 >