This is my sample database:
In my script now, I am adding elements to the list with the following code:
JavaScript
x
11
11
1
import pandas
2
data = pandas.read_excel("Sample database copy.xlsx")
3
name = dict(zip(data["Abbreviation"],data["Name"]))
4
list1 = []
5
incoming_msg = input('Please type what you want to add: ')
6
incoming_msg = incoming_msg.split() # split the string by space
7
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
8
list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
9
else:
10
list1.append(name[incoming_msg[0]])
11
So now if type “2 JO” my list will have two new elements “John” and “John”.
Now I want to do exactly the same but for eliminating objects of a list. I tried to replace the current operator “+=” for “-=” but surprisingly it is not working. Any ideas on how I could solve this?
PS. I need to do it all out of the same input. I cannot ask separately for key and quantity. I want to make a replication of the above code but for removing the objects.
Advertisement
Answer
You could use list.remove()
:
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
JavaScript
1
28
28
1
import pandas as pd
2
3
data = pd.read_excel("Sample database copy.xlsx")
4
name = dict(zip(data["Abbreviation"], data["Name"]))
5
list1 = []
6
7
incoming_msg = input('Please type what you want to add: ')
8
incoming_msg = incoming_msg.split() # split the string by space
9
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
10
list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
11
else:
12
list1.append(name[incoming_msg[0]])
13
14
print('n'.join(list1))
15
16
incoming_msg = input('Please type what you want to delete: ')
17
incoming_msg = incoming_msg.split() # split the string by space
18
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
19
num_to_remove = int(incoming_msg[0])
20
while name[incoming_msg[1]] in list1 and num_to_remove > 0:
21
list1.remove(name[incoming_msg[1]])
22
num_to_remove -= 1
23
else:
24
if name[incoming_msg[0]] in list1:
25
list1.remove(name[incoming_msg[0]])
26
27
print('n'.join(list1))
28
Example Usage:
JavaScript
1
9
1
Please type what you want to add: 4 JO
2
John
3
John
4
John
5
John
6
Please type what you want to delete: 2 JO
7
John
8
John
9