This is a program someone else got:
var1 = ["Orange", "Banana"]
var2 = ["Apple", "Pear"]
var3 = ["Banana", "Pear"]
var4 = ["Grapes", "Orange"]
var5 = ["Orange", "Apple"]
newlst = [var1, var2, var3, var4, var5]
user_fruit = input("Whats ur favorite fruit?: ")
user_fruit = user_fruit.split(
", ") if ", " in user_fruit else user_fruit.split(",")
for fruit in user_fruit:
for flist in newlst:
if fruit in flist:
print(flist)
The output would print out only the list section. but I was wondering if it was able to also print out variable. For example
var1 = ['Orange' , 'Pear']
var4 = ["Grapes", "Orange"]
var5 = ["Orange", "Apple"]
instead of
['Orange' , 'Pear']
["Grapes", "Orange"]
["Orange", "Apple"]
also if possible, I don't want the program to change too much
CodePudding user response:
Whenever you need to print out a variable, the best practice is to simply use a dictionary instead. Dicts are meant for this type of stuff:
# Use a dictionary instead of many lists
newdict = {"var1": ["Orange", "Banana"], "var2": ["Apple", "Pear"], "var3": ["Banana", "Pear"], "var4":["Grapes", "Orange"], "var5":["Orange", "Apple"]}
user_fruit = input("Whats ur favorite fruit?: ")
user_fruit = user_fruit.split(", ") if ", " in user_fruit else user_fruit.split(",")
for fruit in user_fruit:
# Get each key and value in the dictionary
for key, value in newdict.items():
if fruit in value:
# Print out each key and value with a "=" in between
print(key, "=", value)
Output:
var1 = ['Orange', 'Banana']
var4 = ['Grapes', 'Orange']
var5 = ['Orange', 'Apple']
CodePudding user response:
Here is the code of your question
var1 = ["Orange", "Banana"]
var2 = ["Apple", "Pear"]
var3 = ["Banana", "Pear"]
var4 = ["Grapes", "Orange"]
var5 = ["Orange", "Apple"]
variable_strings=['var1','var2','var3','var4','var5']
newlst = [var1, var2, var3, var4, var5]
user_fruit = input("Whats ur favorite fruit?: ")
user_fruit = user_fruit.split(
", ") if ", " in user_fruit else user_fruit.split(",")
pos=0
b=[]
for fruit in user_fruit:
for flist in newlst:
b.append(flist.count(user_fruit[0]))
pos =1
if b[0]==1:
print(variable_strings[0] ' = ' str(var1))
if b[1]==1:
print(variable_strings[1] ' = ' str(var2))
if b[2]==1:
print(variable_strings[2] ' = ' str(var3))
if b[3]==1:
print(variable_strings[3] ' = ' str(var4))
if b[4]==1:
print(variable_strings[4] ' = ' str(var5))
