gpt4 book ai didi

Python 元组 : compare and merge without for loops

转载 作者:太空宇宙 更新时间:2023-11-03 12:00:21 25 4
gpt4 key购买 nike

我有两个列表,每个列表都有超过 100,000 个元组。第一个元组列表中有两个字符串,后者有五个。第一个列表中的每个元组在另一个列表中都有一个具有公共(public)值的元组。例如

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 循环的计算时间 promise ?

最佳答案

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

dict1 = dict(tuple1)
final_list = [(tup[1],dict[tup[1]])+ tup[1:] for tup in tuple2]

关于Python 元组 : compare and merge without for loops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50753076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com