1

I've designed a code that calculates the percentage of 'CG' appears in a string; GC_content(DNA).

Now I can use this code so that it prints the the value of the string with the highest GC-content;

print (max((GC_content(DNA1)),(GC_content(DNA2)),(GC_content(DNA3)))).

Now how would I get to print the variable name of this max GC_content?

user2773611
  • 107
  • 2
  • 10
  • To access a list of names in the global namespace you can use `globals()`. – Shashank Sep 29 '13 at 22:03
  • Variable name is not generally printable, see [retrieving a variable's name in python at runtime?](http://stackoverflow.com/questions/932818/retrieving-a-variables-name-in-python-at-runtime), but the answers here give some nice workarounds. – askewchan Sep 29 '13 at 23:00

3 Answers3

5

You can get the max of some tuples:

max_content, max_name = max(
    (GC_content(DNA1), "DNA1"),
    (GC_content(DNA2), "DNA2"),
    (GC_content(DNA3), "DNA3")
)

print(max_name)
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

If you have many DNA variables you could place them in a list

DNA_list = [DNA1, DNA2, DNA3]

I would coerce them into a dictionary to associate the name with the raw data and result.

DNA_dict = dict([("DNA%i" % i, {'data': DNA, 'GC': GC_Content(DNA)}) for i, DNA in enumerate(DNA_list)])

Then list comprehension to get the data you want

name = max([(DNA_dict[key]['GC'], key) for key in DNA_dict])[1]

This has the benefit of allowing variable list length

Graeme Stuart
  • 5,837
  • 2
  • 26
  • 46
0

You seem to want

max([DNA1, DNA2, DNA3], key=GC_content)

It's not what you asked for but it seems to be what you need.

Veedrac
  • 58,273
  • 15
  • 112
  • 169