简体   繁体   English

使用python搜索将其添加到元组列表

[英]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 ) 我有一个包含两个主要字符串( str1str2 )和一个字符串列表( strlist )的类( cls

python makes the strlist into a tuple so when i want to append to it i use python使strlist成为一个元组,所以当我想附加到它时,我使用

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 可能不是最好的选择,但它是我对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 现在我使事情变得更复杂了,我有cls( clslist )列表,我想向strlist添加另一个字符串,其中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 如何创建一个搜索,以便在clslist中搜索匹配项,如果找到,则将新字符串添加到strlist

EDIT 1 编辑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 我想在clslist中找到str1 = aaa和str2 = bbb的cls,然后将另一个字符串添加到str列表中

so i will end up like this ("aaa","bbb",("123","456","789")) 所以我最终会这样(“ 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 () Python不会将strlist变成一个元组,您正在传递一个元组。如果您想要一个列表,只需使用[]而不是()

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

Searching your clslist is easy 搜索您的clslist很容易

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. ,之前的)手段("baz",)是一个元组,并可以添加元组。 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. list.append不同,这将创建一个新的元组,因此效率不如将所有旧的引用复制到新的元组中一样。

Since clslist is unsorted your search will need to be linear. 由于clslist未排序,因此您的搜索将需要是线性的。

For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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