2

For example, we have the scores of three courses stored in LIST.

English, Maths, Physics = 89, 92, 93
LIST = [English, Maths, Physics]
for i in range(len(LIST)):
    print(LIST[i])

And I want the print style to be like English, 89, Maths, 92, Physics, 93. Here is a solution that defines another list LIST_name

English, Maths, Physics = 89, 92, 93
LIST = [English, Maths, Physics]
LIST_name = ['English', 'Maths', 'Physics']
for i in range(len(LIST)):
    print(LIST_name[i], LIST[i])

I am wondering if there is a built-in function or some other tricks that can help me directly convert English to "English", without defining LIST_name? And if so, how? As Barmar commented below, what I am looking for is how to go from a value to the name of the variable it came from?

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
guorui
  • 871
  • 2
  • 9
  • 21
  • 5
    Use a dictionary instead of a list. `{"English": English, "Maths": Maths, "Physics": Physics}` – Barmar Jul 18 '19 at 03:00
  • There's no way to go from a value to the name of the variable it came from. – Barmar Jul 18 '19 at 03:02
  • 1
    Or learn enough programming to create a class for the objects which contains their name, score, and other pertinent information for each instance. – tripleee Jul 18 '19 at 03:02
  • @Barmar Thanks for replying me, but this is not what I am looking for. – guorui Jul 18 '19 at 03:02
  • 1
    The same value can be held in many variables. – Barmar Jul 18 '19 at 03:02
  • What you're looking for is not possible in Python, or most programming languages. – Barmar Jul 18 '19 at 03:03
  • 2
    Then [edit] your question to explain which actual problem you are hoping to solve and why a dictionary is unsuitable. – tripleee Jul 18 '19 at 03:03
  • 1
    Maybe search for similar questions, and discover that basically every time a beginner asked for something like this, they ended up using a dictionary and understanding why this is a better solution. – tripleee Jul 18 '19 at 03:05
  • @tripleee As Barmar said, and his description is much more precise. I want to achieve this goal that " go from a value to the name of the variable it came from". – guorui Jul 18 '19 at 03:06
  • 3
    The general feeling among experienced programmers is that if you need to do what you're trying to do, you're doing it wrong. Programming languages have data structures like dictionaries for a reason. – Barmar Jul 18 '19 at 03:06
  • @Barmar Thanks again for these helpful comments and I really learned a lot from them. – guorui Jul 18 '19 at 03:09
  • Also check [this thread](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string/18425523) out for why you cannot get variable names in Python. – Robert Vunabandi Jul 18 '19 at 03:15

3 Answers3

3

You can have a method that takes variable keyword args as input and gives you dict with key value pair

 def marks(**m):
  return m

 d=marks(English=90,Maths=100,Physics=90)  #call method with keyword args
 print(d)

Output :

   {'English': 90, 'Maths': 100, 'Physics': 90}

You can also iterate dict

for k,v in d.items():
  print(k,v,sep=', ')

Output

English, 90
Maths, 100
Physics, 90
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
2

Adding to @Deadpool's answer, you can use:

>>> dict(English=82,Maths=92,Physics=93)
{'English': 82, 'Maths': 92, 'Physics': 93}
>>> 

More matching your case would be:

>>> print('\n'.join(map(lambda x: ', '.join(map(str, x)), dict(English=82,Maths=92,Physics=93).items())))
English, 82
Maths, 92
Physics, 93
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Define a class that represents the object that you're working with and override the __str__ (and optionally __repr__) function(s):

class Course(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score
    def __str__(self):
        return self.name + ', ' + str(self.score)
    def __repr__(self):
        return '<{0}.{1} object at {2}> {3}'.format(self.__class__.__module__,
                                            self.__class__.__name__,
                                            hex(id(self)), str(self))

English, Maths, Physics = list(map(lambda x:Course(*x), zip(['English','Math','Physics'],[89,92,93])))

Or, combine with the other suggestions using dict:

English,Maths,Physics = list(map(lambda x:Course(*x), dict(English=82,Maths=92,Physics=93).items()))

And then you can:

>>> LIST = [English, Maths, Physics]
>>> for i in LIST:
...     print(i)
...
English, 89
Math, 92
Physics, 93
David Zemens
  • 53,033
  • 11
  • 81
  • 130