+ 2
Is there a way to print a list when you have its name as a string?
Say we have the list l= [1,2,3] and the string s= 'l'. Is there a way to get s to print l?
9 Antworten
+ 6
it depends on in wich scope is the variable...
if it's a global variable in the current module:
print(global()[string_variable_name])
if it's a local variable:
print(local()[string_variable_name])
if it's a variable in another module:
import other_module
print(getattr(other_module,string_variable_name))
+ 2
another option instead of eval could be using a dictionary or a class.
dictionary example:
dict[‘I’] = [1,2,3]
class example:
class myClass():
pass
myString = myClass()
myString.I = [1,2,3]
+ 1
l = [1,2,3]
s = 'l'
print(eval(s))
+ 1
eval == evil
well, eval() works too, but should be avoided as could be used to do anything else (unsafe) if the string is given by untrusted user ^^
+ 1
_dict = {"l" : [1,2,3,4]}
s = "l"
print(_dict[s])
This si the best way i just found for doing that,
It works, because you can call a dictionary Index by string.
For accesing a value from the list you just:
_dict[s][value_index]
0
In any programming language the same pedagogy applies - iterate through the list and list the items 🌻
0
No it doesn't print list of l it just print letter l
0
Yeah!!!! print(s)
- 1
Yah.
Answer the same, as Yr. code. sum & findings. All programming languages code work in similar format {fashion} °~° ;,.
😝😒👥👥📜