smitty23
smitty23

Reputation: 51

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)

Upvotes: 4

Views: 129

Answers (3)

Subham
Subham

Reputation: 411

Another approach

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 )

Upvotes: 0

jpp
jpp

Reputation: 164623

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

Upvotes: 0

user3483203
user3483203

Reputation: 51165

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

Upvotes: 9

Related Questions