简体   繁体   中英

add to a list in tuple with search in python

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM