【发布时间】:2020-07-10 07:03:34
【问题描述】:
我正在尝试编写一些高效的 python 代码来识别同时出现在多个列表中的项目。例如,在列表字典中
list_of_lists = {'lista':list('abcdefhmqr'),
'listb':list('abdgklmr'),
'listc':list('abcdgjkmr'),
'listd':list('abcdglmrt'),
'liste':list('admoprst')}
“adrm”一起出现在所有五个列表中,而“abdm”、“abdr”、“abmr”和“bdmr”一起出现在四个列表中,四个字母的许多组合出现在三个或两个列表中。
代码如下:
def make_dict(lists):
# creates a dictionary with each unique item as the key,
# and a set of lists the item appears on as the value
letter_dict={}
for item in lists.items():
for letter in item[1]:
if letter in letter_dict:
letter_dict[letter].add(item[0])
else:
letter_dict[letter] = set([item[0]])
return OrderedDict(sorted(letter_dict.items(),key=lambda x:x[0]))
def find_matches(dictionary):
# takes a dictionary with tuples of list elements as keys
# and lists they appear on as values, and finds the intersection with
# the master list of elements and their lists
matches={}
for key in dictionary.keys():
index_of_key = index_of_attr_keys.index(key[-1])
for next_key in islice(master_list,index_of_key+1,None):
intersection = dictionary[key] & master_list[next_key]
if len(intersection)>1:
new_key = set(key)
new_key.add(next_key[0])
new_key = tuple(sorted(new_key))
matches[new_key] = intersection
return matches
master_list = make_dict(list_of_lists)
index_of_attr_keys = sorted(master_list.keys())
我可以迭代地制作带有两个、三个、四个等项的元组键的字典
doubles = find_matches(master_list)
triples = find_matches(doubles)
quads = find_matches(triples)
我的代码适用于这个玩具示例,但是当我在我的实际数据集上运行它时它并不是特别快,该数据集包含出现在数百个列表中的 84,000 多个唯一元素。从我的 84,000 多个独特元素列表开始,生成一个包含 120 万对的列表需要一个小时,这些对一起出现在多个列表中,并且事情会变得更长。我想知道是否有更快的方法来做到这一点。
【问题讨论】:
-
预期输出是什么?
-
输出将是一个元素组合列表,我可以对其进行排序以找到最常一起出现的组合。
-
所以你想要 adrm、'abdm'、'abdr'、'abmr' 和 'bdmr' 还是只需要 adrm ?出现 5 次的广告会发生什么情况?
-
一些示例问题是,是否有任何 10 个项目一起出现在至少 20 个列表中?最常同时出现的 5 组列表中出现了多少个列表?之类的东西。我不是在寻找出现在 every 列表中的项目。我已经知道,任何人都不太可能这样做。但是有些群体肯定会一起出现。
标签: python list ordereddictionary