Python元组:无需for循环进行比较和合并

2024-09-30 18:22:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个超过100000元组的列表。第一个元组列表中有两个字符串,后者有五个字符串。第一个列表中的每个元组都有一个元组,另一个列表中有一个公共值。例如

tuple1 = [('a','1'), ('b','2'), ('c','3')]
tuple2 = [('$$$','a','222','###','HHH'), ('ASA','b','QWER','TY','GFD'), ('aS','3','dsfs','sfs','sfs')] 

我有一个函数,可以删除多余的元组值并匹配重要信息:

def match_comment_and_thread_data(tuple1, tuple2):
    i = 0
    out_thread_tuples = [(b, c, d, e) for a, b, c, d, e in tuple2] 
    print('Out Thread Tuples Done')
    final_list = [x + y for x in tuple2 for y in tuple1 if x[0] == y[0]]
    return final_list

应该返回:

 final_list = [('a','1','222','###','HHH'), ('b','2','QWER','TY','GFD'), ('c','3','dsfs','sfs','sfs')]

然而,名单却长得离谱。在比较和匹配元组值时,有没有办法绕过for循环的计算时间承诺?你知道吗


Tags: 字符串in列表forlistfinal元组sfs
2条回答

通过使用字典,这可以在O(n)中完成

dict1 = dict(tuple1)
final_list =  [(tup[1],dict[tup[1]])+ tup[1:] for tup in tuple2]
tuple1 = [('a','1'), ('b','2'), ('c','3')]
tuple2 = [('$$$','a','222','###','HHH'), ('ASA','b','QWER','TY','GFD'), ('aS','3','dsfs','sfs','sfs')]

def match_comment_and_thread_data(tuple1, tuple2):
    i = 0
    out_thread_dict = dict([(b, (c, d, e)) for a, b, c, d, e in tuple2])
    final_list = [x + out_thread_dict.get(x[0],out_thread_dict.get(x[1])) for x in tuple1]
    return final_list

用字典代替你的查找时间是O(1)。。。您仍然需要访问列表1中的每个项目。。。但是比赛很快。。。尽管你需要比3更多的值才能得到好处

相关问题 更多 >