mimat mimat - 2 months ago 6
Python Question

Assigning a set properties to each element of a list python

I have a list containing unique items (names if you will) that changes every time I run my script. All of these items have some calculated properties that are modified during the script. For example 'S1' will have pos = 55 and ori = 'R'. I'd like an easy way to access these properties based on their name.

What is the best way to 'assign' these properties? I have been looking around and dictionaries do not seem be the right way to go forward so I tried with classes and made the following non-functional code code:

class Primer: #contains all properties of a primer
def __init__(self):
""" Contains all properties of the primer """
self.pos = 0 #outermost 5' position in sequence to bind
self.ori = '' #F(orward) or R(everse)


primer_list = ['S', 'M1', 'M2', 'M3', 'E']

for i in primer_list:
i = primer()

print S.pos #this should give me the pos value of 'S'


Am I on the right track but missing something or is there a better way to do this?

EDIT
I forgot to mentioned that I also need to get my values back somehow. Equally clueless how to do this

print primer_list[0].pos #should give me the pos value of S in my example

Answer

You were having problems with the list, you didn't actually replace the old values with the created instance. I also added a name field so you could keep track of each instance.

class Primer: #contains all properties of a primer
    def __init__(self, name):
        """ Contains all properties of the primer """
        self.name = name
        self.pos = 0 #outermost 5' position in sequence to bind
        self.ori = '' #F(orward) or R(everse)

    def __str__(self):
        return self.name

primer_list = ['S', 'M1', 'M2', 'M3', 'E']
new_primer = [Primer(x) for x in primer_list]

for i in new_primer:
    print i
    print i.pos
    print i.ori
Comments