Reputation: 3
I am trying to work out if this is posible. I want to print the varible name from a list. Here is my code
brisbane=[1,2,3,4]
sydney=[2,5,8,34,6,2]
perth=[2,4,3]
towns=[brisbane,sydney,perth]
I am doing some maths, then with these numbers I want to take the string 'brisbane' from the towns list and use it somewhat like this.
print 'the town witht the most rain was', towns[0], '.'
and print this as 'the town with the most rain was brisbane.'
Upvotes: 0
Views: 89
Reputation: 2202
it is not possible to print a variable name at least not in the way you are presenting above.
Source: Getting the name of a variable as a string
In your case you could instead create a dictionary, like this:
towns = {}
towns['brisbane'] = [1, 2, 3, 4]
towns['sydney'] = [2, 5, 8, 34, 6, 2]
towns['perth'] = [2, 4, 3]
print(towns)
{'sydney': [2, 5, 8, 34, 6, 2], 'perth': [2, 4, 3], 'brisbane': [1, 2, 3, 4]}
Upvotes: 1
Reputation: 8314
You can definitely do so. Check out the string formating documents here: https://docs.python.org/2/library/string.html#format-examples
for your particular example, it would just be
print ("the town with the most rain was {0}".format(towns[0]))
Upvotes: 0
Reputation: 90889
I believe it would be easier for you to use a dictionary in this case , something like -
d = {'brisban':[1,2,3,4],
'sydney':[2,5,8,34,6,2],
'perth':[2,4,3]}
Then you can store the keys
in the list towns , Example -
towns = list(d.keys())
And then when doing your maths , you can call each town's values as - d[<town>]
, Example - d['brisbane']
.
And after that you can get the corresponding town name from towns
list.
Upvotes: 3