简体   繁体   中英

Python 3 - Multiplying numbers in a list by two

The purpose of the code I'm asked to complete is to receive the input of the given inventories, return them as given in a list in one line. Then on a second line, duplicate the list but this time double the numbers.

The given inputs are

Choc 5; Vani 10; Stra 7; Choc 3; Stra 4

The desired output is:

[['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]]
[['Choc', 10], ['Vani', 20], ['Stra', 14], ['Choc', 6], ['Stra, 8]]

I've managed to successfully get the desired output for the first line, but am struggling with how to successfully compete the second.

This is the code:

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)

Since you already have the first line done, you can use a simple list comprehension to get the second line:

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

Output:

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

Here are the usual one-liners in case you wish to avoid explicit loops:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM