访问并打印变量和列表python



这是别人得到的程序:

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)

输出将只打印出列表部分。但我想知道它是否也能打印出变量。例如

var1 = ['Orange' , 'Pear']
var4 = ["Grapes", "Orange"]
var5 = ["Orange", "Apple"]

而不是

['Orange' , 'Pear']
["Grapes", "Orange"]
["Orange", "Apple"]

如果可能的话,我不希望程序改变太多

当您需要打印出一个变量时,最好的做法是简单地使用dictionaryDicts适用于这种类型的东西:

# 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)

输出:

var1 = ['Orange', 'Banana']
var4 = ['Grapes', 'Orange']
var5 = ['Orange', 'Apple']

以下是您的问题代码:-

# all lists
var1 = ["Orange", "Banana"]
var2 = ["Apple", "Pear"]
var3 = ["Banana", "Pear"]
var4 = ["Grapes", "Orange"]
var5 = ["Orange", "Apple"]
# this variable will help to access next element in newlst variable 
position=0
# this variable contains the data about the input occurrence in all lists (var1,var2,var3,var4,var5).
occurrence_of_input_in_all_lists=[]
# this variable contains all lists name (var1,var2,var3,var4,var5) in string form
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(",")
for fruit in user_fruit:
for flist in newlst:
occurrence_of_input_in_all_lists.append(flist.count(user_fruit[0]))# appending the occurrence of input received if the input dosen't exists in flist it will append '0' to occurrence_of_input_in_all_lists  or if it exists then '1'  will be append to occurrence_of_input_in_all_lists.  
if occurrence_of_input_in_all_lists[position]==1: #checking  the occurrence of input received
print(variable_strings[position]+' = '+str(newlst[position]))#printing the final output
position+=1 #adding 1 to position to access next element from the newlst variable

相关内容

  • 没有找到相关文章