Convert User Input into a List name - python

Here is what I have so far:
TotalLists=int(input("How many Lists are you making?"))
TotalListsBackup=TotalLists
Lists=[]
while TotalLists>0:
ListName=input("What would you like to call List Number "+str(TotalLists))
Lists.append(ListName)
TotalLists=TotalLists-1
TotalLists=TotalListsBackup-1
while TotalLists>=0:
Lists[TotalLists] #I would like to create actual lists out of the list names at this step but I dont know how...
TotalLists=TotalLists-1
TotalLists=TotalListsBackup-1
print("Here are your Lists: ")
while TotalLists>=0:
print(Lists[TotalLists])
TotalLists=TotalLists-1
I want to be able to:
create a List out of the List Names
The code to be able to make as many lists as the user wants to without a cap
For example, I want to input: Grocery,
The code will create a list Called Grocery
Solutions I have thought of:
Arrays? (I have never used them, I am very new to Python Programming and I dont know too much)
Lists of Lists? (Not sure how to do that. Looked it up, but didn't get a straight answer)
Using Variables, Creating a list with a name like:
List1[]
and have varible called:
List1Name=input("What would you like to call list 1?")
I do not know how to create an infinite number of lists using this way though.
If you have any questions please ask, for I know I am not good at explaining.

It's interesting that you have tagged the question "dictionary" but didn't mention that in your post. Did somebody tell you to use a dictionary? That's exactly what you should be doing, like this (assume TotalLists is already defined):
d = {}
for _ in range(TotalLists): # The same loop you have now
ListName = input("whatever...")
d[ListName] = []
At the end of this you have a dictionary d containing keys that are the user-entered names, and values that are empty lists. The number of dictionary entries is TotalLists. I'm ignoring the possibility that the user will enter the same name twice.

You're solving an XY problem. There's no need to ask for the number of lists in advance. I would recommend using a dictionary:
>>> lists = {}
>>> while 1:
... newlist = input("Name of new list (leave blank to stop)? ")
... if newlist:
... lists[newlist] = []
... while 1:
... newitem = input("Next item? ")
... if newitem:
... lists[newlist].append(newitem)
... else:
... break
... else:
... break
...
Name of new list (leave blank to stop)? groceries
Next item? apples
Next item? bananas
Next item?
Name of new list (leave blank to stop)? books
Next item? the bible
Next item? harry potter
Next item?
Name of new list (leave blank to stop)?
>>> lists
{'groceries': ['apples', 'bananas'], 'books': ['the bible', 'harry potter']}

Related

Edit list element in multilist - Python

I am using python 3.x, I have the following problem, using the keyboard the user enters certain data and fills N lists to create a contact list, then in a list I collect all the data of the lists, I need to modify the data of each list, (I already have it, I modify the data of a list with a specific value using a for) Example, Names list, I modify Andrew's name, but in the Contacts list, there is all Andrew's information (phone, mail, etc), but I just need to modify in the Contacts list, the value of Andrew
I have all this list:
names = []
surnames = []
phones = []
emails = []
addresses = []
ages = []
salaries = []
genres = []
contacts = []
# and use the append to add the data into the contacts list
contacts.append ([names, surnames, phone numbers, emails, addresses, ages, salaries, genders])
Then I update the info of one contact
search = input(Fore.LIGHTBLUE_EX + "Type the name of the contact you want update: ")
for i in range(len(names)):
if (names[i] == search):
try:
names[i] = input(Fore.MAGENTA + "Type the New name: ")
names[i] = nombres[i].replace(" ", "")
if names[i].isalpha() == True:
print(Fore.GREEN + "Already saved, congrats.")
pause= input(Fore.LIGHTGREEN_EX + "Press enter to exit")
But I dont know how to update the name in the List of contacts.
When you call contacts.append(), you add a list of lists to a list, so your contacts list will look something like this:
contacts = [[[names[0], names[1], ...], [...], [...]]]
It's unnecessary to have a list of one item nested in another list, so I would just call contacts.append() and pass each list (names, surnames, etc.) to the method, which allows for easier indexing.
Since the list names would be the first item in the list contacts (contacts[0]), you could do one of two things (there may be more, but these are off the top of my head):
Reassign the specific index to a new value, using nested-list indexing (contacts[0][0] = "updated name" would update the first item of the names list to "update name")
Reassign the entire nested list to a new list (contacts[0] = new_name_list would reassign contacts[0], formerly the names list, to new_name_list)
On a side note: In this case, I would recommend dictionaries over lists, as it will be easier to keep track of what is being reassigned/modified.
contacts = {
"names": names,
"surnames": surnames,
...
}
Doing this will make it more clear which list your are referring to; contacts[0] doesn't give much information, but contacts["names"] informs readers that you are referring to the names list. This is solely for cleaner code; there isn't much difference in functionality.

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

How can I take a text file and create a triple nested list from it with tkinter python

I'm making a program that allows the user to log loot they receive from monsters in an MMO. I have the drop tables for each monster stored in text files. I've tried a few different formats but I still can't pin down exactly how to take that information into python and store it into a list of lists of lists.
The text file is formatted like this
item 1*4,5,8*ns
item 2*3*s
item 3*90,34*ns
The item # is the name of the item, the numbers are different quantities that can be dropped, and the s/ns is whether the item is stackable or not stackable in game.
I want the entire drop table of the monster to be stored in a list called currentDropTable so that I can reference the names and quantities of the items to pull photos and log the quantities dropped and stuff.
The list for the above example should look like this
[["item 1", ["4","5","8"], "ns"], ["item 2", ["2","3"], "s"], ["item 3", ["90","34"], "ns"]]
That way, I can reference currentDropTable[0][0] to get the name of an item, or if I want to log a drop of 4 of item 1, I can use currentDropTable[0][1][0].
I hope this makes sense, I've tried the following and it almost works, but I don't know what to add or change to get the result I want.
def convert_drop_table(list):
global currentDropTable
currentDropTable = []
for i in list:
item = i.split('*')
currentDropTable.append(item)
dropTableFile = open("droptable.txt", "r").read().split('\n')
convert_drop_table(dropTableFile)
print(currentDropTable)
This prints everything properly except the quantities are still an entity without being a list, so it would look like
[['item 1', '4,5,8', 'ns'], ['item 2', '2,3', 's']...etc]
I've tried nesting another for j in i, split(',') but then that breaks up everything, not just the list of quantities.
I hope I was clear, if I need to clarify anything let me know. This is the first time I've posted on here, usually I can just find another solution from the past but I haven't been able to find anyone who is trying to do or doing what I want to do.
Thank you.
You want to split only the second entity by ',' so you don't need another loop. Since you know that item = i.split('*') returns a list of 3 items, you can simply change your innermost for-loop as follows,
for i in list:
item = i.split('*')
item[1] = item[1].split(',')
currentDropTable.append(item)
Here you replace the second element of item with a list of the quantities.
You only need to split second element from that list.
def convert_drop_table(list):
global currentDropTable
currentDropTable = []
for i in list:
item = i.split('*')
item[1] = item[1].split(',')
currentDropTable.append(item)
The first thing I feel bound to say is that it's usually a good idea to avoid using global variables in any language. Errors involving them can be hard to track down. In fact you could simply omit that function convert_drop_table from your code and do what you need in-line. Then readers aren't obliged to look elsewhere to find out what it does.
And here's yet another way to parse those lines! :) Look for the asterisks then use their positions to select what you want.
currentDropTable = []
with open('droptable.txt') as droptable:
for line in droptable:
line = line.strip()
p = line.find('*')
q = line.rfind('*')
currentDropTable.append([line[0:p], line[1+p:q], line[1+q:]])
print (currentDropTable)

How to flip list to dictionary python

can you help me to flip list to dictionary
shopping_list = raw_input("Enter you Shopping List: ").title().split(',')
i need to flip this list to dictionary
and i dont know how much product the user want to input
This question is a bit ambiguous as you did not provide example input or output. I will assume that you are going to ask the user multiple times to enter in an item and how many they need separated by a comma. If the input changes, then I will edit my answer.
dictionary = {}
item, numberOfItems = raw_input("Enter your Shopping List: ").title().split(',')
dictionary[item] = numberOfItems
This is assuming that no matter what, your input comes in the form of:
banana,3
carrot,7
pack of gum,9
Edit
Since I see what the input is, I can answer this better.
The input string someone will input follows this pattern:
item1,3,item2,7,item3,20,item4,5
So we need to split the input every 2 items.
my_list = raw_input("Enter your Shopping List: ").title().split(',')
composite_list = [my_list[x:x+2] for x in range(0, len(my_list),2)]
This should set composite_list as such.
[[item1,3], [item2,7], [item3,20], [item4,5]]
Now all we need to do is loop through composite_list
for pair in composite_list:
print('({}:{})'.format(pair[0], pair[1]))
The output will now look like:
(item1:3)

I'm trying to get python to print a random word from the list but instead it just prints the whole list. Can someone suggest any ways to fix this?

importing random
import random
asking the user to input their friend's names
friends = []
friend = input("Type in your first friends name:")
friend2 = input("Type in your 2nd friends name:")
appending friends list
friends.append([friend,friend2])
this is where i tell python to choose a random word from the list
bestfriend = random.choice(friends)
print (bestfriend)
OUTPUT:
Type in your first friends name: Aaron
Type in your 2nd friends name: Josh
[' Aaron', ' Josh']
You are appending a list of friends into the list. As a result you are getting a list of lists.
Instead append each friend one by one. You can even use a list comprehension to make a list of friends:
friends_count = 2
friends = [input("Type in your friend's name:") for _ in range(friends_count)]
print(random.choice(friends))
append method adds the submitted value (which in your case is a list [friend,friend2])
to the target list.
extend adds all elements from the submitted argument. So, use extend method instead:
>>> friends.extend([friend,friend2])
It will be equivalent to
>>> friends += [friend, friend2]

Categories

Resources