Python 列表/集合中的查找和元素的修改

Python 列表/集合中的查找和元素的修改,python,list,set,lookup,nested-lists,Python,List,Set,Lookup,Nested Lists,我创建了一个函数,该函数可以查找列表中的项目是否通用,如果是,则修改这些列表中的特定元素(列表是嵌套的)。问题是列表中的查找是O(n)。如果我有大量的列表,我会花太多的时间在查找上。下面是使用列表的函数: def union_finder(list_of_lists_unions): while list_of_lists_unions: processed_list = list_of_lists_unions.pop(0) for item in pr

我创建了一个函数,该函数可以查找列表中的项目是否通用,如果是,则修改这些列表中的特定元素(列表是嵌套的)。问题是列表中的查找是O(n)。如果我有大量的列表,我会花太多的时间在查找上。下面是使用列表的函数:

def union_finder(list_of_lists_unions):
    while list_of_lists_unions:
        processed_list = list_of_lists_unions.pop(0)
        for item in processed_list:
            for loc_list,pointer_list in enumerate(list_of_lists_unions):
                for location,iteration in enumerate(pointer_list):
                    if item == iteration:
                        #if condition then change the element which matches on the lists
                        if(something):    
                            count +=1
                            index_dict[item] = count
                            list_of_lists_unions[loc_list][location] = str(index_dict[item]) + str('@')
该功能工作正常。例如,如果我将以下内容作为输入:

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30], [1, 2, 3, 4, 29, 30], [100200300,28,29,30]]

编辑


我尝试使用set(),因为查找复杂性是O(1)(如文档所述)。问题是我使用了列表,这样我可以修改迭代中的元素。集合不允许我修改其中的特定元素。我的想法是在集合中找到我想要的项目,然后将其转换回列表,进行我想要的修改,然后将其重新转换回集合。但这是否有效?有没有其他方法可以使用集合的查找速度?列表的查找复杂度是O(N),这太多了,因为我的列表有时非常长,如果我尝试比较两个列表len(list1)=m,len(list2)=N,我会得到m*N个查找(s中的x)

你所说的“查找”是什么意思?你似乎在为列表编制索引,这是
O(1)
。我所说的查找是指搜索(s中的x)而不是强制转换,为什么不维护一个列表和一个集合,使用前者进行编写,使用后者进行查找我认为你是对的。我试试看。