How can I add two or more elements to a list from a single input in Python?

What my script is doing now is adding elements to a list. For example, if the user types “JO”, I will add “John” to the list. What I want to do now is that, if the user types “2 JO”, I add two elements to the list: “John” and “John”. This is how the database looks like now:

Sample database copy.png

This is the code now:

import pandas
data = pandas.read_excel("Sample database copy.xlsx")
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input(Please type what you want to add: )
list1.append(name[incoming_msg])

I need to do it all from the same input, I cannot ask separately for quantity and abbreviation. I wanted to know if there is any library that can do this somehow easily because I am a beginner coder. If there is no library but you have any idea how I could solve it, it would be awesome as well.

Thank you so much in advance!

Answer

you can use string.split() to split the string by space into a list then use the first element to multiply a list that contains the value from the dictionary and increment it to the result list. see the code

name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input('Please type what you want to add: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
    list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
else:
    list1.append(name[incoming_msg[0]])

Leave a Reply

Your email address will not be published. Required fields are marked *