0
votes

i have a class (cls) with 2 main strings (str1, str2) and a list of strings (strlist)

python makes the strlist into a tuple so when i want to append to it i use

tmp=list(strlist)
tmp.append(addToList)
self.list=tmp

may not the best option but its the only one i could make with low knowledge of python

now i make things more complicated i have list of cls (clslist) and i want to add another string to the strlist where str1 = A && str2 = B

how do create a search that will search for a match in the clslist and if found will add the new string to strlist

EDIT 1

class cls ():
    def __init__ (self,str1,str2,strlist):
        self.str1 = str1
        self.str2 = str2 
        self.strlist = strlist

and the main

def main():
    clslist =[]
    clslist.append(cls ("aaa","bbb",("123","456"))

i want to find the cls in the clslist where str1 = aaa and str2 = bbb and then add another string to the str list

so i will end up like this ("aaa","bbb",("123","456","789"))

2
What are A and B? You also say 'python makes the strlist into a tuple', where and why? Please post your class, otherwise it's very hard to work out what is going on. - Gareth Latty
@Lattyware A and B are strings as well - Iakovl

2 Answers

3
votes

Python doesn't make strlist a tuple, you are passing a tuple in. If you want a list just use [] instead of ()

clslist.append(cls("aaa", "bbb", ["123","456"])

Searching your clslist is easy

for item in clslist:
    if item.str1 == A and item.str2 == B:
        # do something
        item.strlist.append(otherstring)

If you do need to extend a tuple, you can do it like this

>>> ("foo", "bar")+("baz",)
('foo', 'bar', 'baz')

The , before the ) means ("baz",) is a tuple, and you can add tuples. Unlike list.append, this will create a new tuple, so is not as efficient as it needs to copy all the old references into the new tuple.

1
votes

Since clslist is unsorted your search will need to be linear.

For example:

for i in clslist:
    if i.str1 == A and i.str2 == B:
        i.strlist.append(whatever)