I need to acess a variable in list for example
var1=[Orange,Banana]
var2=[Apple,Pear]
var3=[Banana,Pear]
var4=[Grapes,Orange]
var5=[Orange,Apple]
user_fruit = str(input("Whats ur favorite fruit?: "))
*user inputs Orange, Pear
How do I somehow print out var1, var2 var3, var5, (like print out all variable with the user's input within their lists'.
CodePudding user response:
You can achieve this using locals, although it is almost never a good idea. It is better to structure your data as a dict in the first place, e.g. {"var1": ["Orange", "Banana"]}.
var1=["Orange","Banana"]
var2=["Apple","Pear"]
var3=["Banana","Pear"]
var4=["Grapes","Orange"]
var5=["Orange","Apple"]
# dict of all locally defined variables that start with "var"
my_vars = {k: v for k, v in locals().items() if k.startswith("var")}
# {'var1': ['Orange', 'Banana'],
# 'var2': ['Apple', 'Pear'],
# 'var3': ['Banana', 'Pear'],
# 'var4': ['Grapes', 'Orange'],
# 'var5': ['Orange', 'Apple']}
# user_fruit = str(input("Whats ur favorite fruit?: "))
user_fruit = "Banana"
# print all varnames containing user_fruit
for k, v in my_vars.items():
if user_fruit in v:
print(k)
# prints var1 and var3
# for faster lookup, you can preprocess the data so that each fruit
# encodes a list of vars containing it
from collections import defaultdict
fruit_to_var = defaultdict(list)
for k, v in my_vars.items():
for fruit in v:
fruit_to_var[fruit].append(k)
# another lookup:
print(fruit_to_var["Banana"])
CodePudding user response:
If you want just access to name of variables (for example Orange), you can define them as string in one list. Then for searching a name in list, You can do this:
user_input = str(input("Whats ur favorite fruit?: "))
mylist = ['Orange', 'Banana', 'Apple' ,'Pear']
print(mylist[mylist == user_input])
But if you want name of variable (and its value), this link can help you:
How can you print a variable name in python?
CodePudding user response:
I didn't understand your question. Could you please be more specific? What I have figured out, I tried to solve it. Here is the snippet.
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)
