0

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.'

2
  • 1
    You don't want to try to do that. Use a dictionary. Commented Aug 5, 2015 at 5:01
  • If you want brisbane in your string then you have give it as a string. Check this out stackoverflow.com/a/18425275/5039470 Commented Aug 5, 2015 at 5:06

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks This is exactly what I was looking for. Learned something new today.
1

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]}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.