Python 3 - 将列表中的数字乘以二

4

我被要求完成的代码的目的是接收所给库存的输入,并将它们作为一个列表在一行中返回。然后在第二行,复制该列表,但这次将数字加倍。

所给的输入为:

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)
3个回答

9
由于您已经完成了第一行,您可以使用简单的列表推导式获取第二行:
x = [[i, j*2] for i,j in x]
print(x)

输出:

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

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

0

另一种方法

string = "Choc 5; Vani 10; Stra 7; Choc 3; Stra 4"
newList = []

for i in string.split(";"):
    temp_list = i.split()
    for idx, val in enumerate(temp_list):
        if val.isdigit():
            temp_list[idx] = int(val) * 2
    newList.append(temp_list)
print(newList )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接