gpt4 book ai didi

Python - 将交易数据加载到列表列表中,计算每个字符串的出现次数

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:16 26 4
gpt4 key购买 nike

由于其中有一项家庭作业,我正在重新使用 Python,并且正在寻求有关加速我的代码部分的帮助。由于没有提供我的想法,我的上一篇文章被否决了,所以这次我会做得更好。

我有一个采购交易的文本文件,如下所示:

A B C D E F
A E F G H I J K
A B D E F G H
B C D F G H
G H I K J
G H I J
B C D H J K
B C D H K
A C E G I K
A B D F G H I
A B C D E F G H I J K
A B C D E
C D F G
C E F G H I
C D E J K
J K
G H I J K
A B D
A C D K
A B D I J K
A B C E F G
F G I J K
A F G K
B C E F G H
A D E
A B
C D E F
C E F G H I J
I J K
E F H I J K

其中每个字母对应于对特定产品的购买,每一行都是一次交易(对于第一行,某人购买了产品 A B C D E 和 F)。我需要对每种产品的购买次数进行初步统计,然后创建至少购买了 S 次的商品列表。这是我的代码的样子:

import itertools
import operator

item_data_lol = []
with open("test_file.txt") as inputfile:
for line in inputfile:
item_data_lol.append(line.strip().split(','))

# this is what item_data_lol loads in as
# [['A B C D E F'], ['A E F G H I J K'], ['A B D E F G H'], ['B C D F G H'], ['G H I K J'], ['G H I J'], ['B C D H J K'], ['B C D H K'], ['A C E G I K'], ['A B D F G H I'], ['A B C D E F G H I J K'], ['A B C D E'], ['C D F G'], ['C E F G H I'], ['C D E J K'], ['J K'], ['G H I J K'], ['A B D'], ['A C D K'], ['A B D I J K'], ['A B C E F G'], ['F G I J K'], ['A F G K'], ['B C E F G H'], ['A D E'], ['A B'], ['C D E F'], ['C E F G H I J'], ['I J K'], ['E F H I J K']]

S = 14

# initialize dictionary to count frequency of individual items
first_lookup = {}

# loop over each row, then each element, obtaining a total element count for each element
for line in item_data_lol:
line = line[0]
for item in line.split():
if item in first_lookup.keys():
first_lookup[item] += 1
else:
first_lookup[item] = 1


# Get list of frequent items
frequent_items = []
for this_key, this_value in first_lookup.iteritems():
if this_value > support_threshold:
frequent_items.append(this_key)

print(first_lookup)
print(frequent_items)

这种代码结构适用于我的小型数据集,但是当我在提供的完整 txt 文件上运行我的程序时,这需要很长时间。这段代码只是我必须编写的更大算法(用于查找频繁项集的先验算法)的一小部分,因此令人担忧的是,第一部分所花费的时间与它所花的时间一样长。如果我可以使用不同的 python 函数加快这部分代码的速度(我主要使用 for 循环和 if 情况,因为我对 python 生锈并且不记得很多函数),那么我可能可以加快我程序的后面部分以及。

感谢任何关于如何加快速度的想法

最佳答案

可悲的是,您遇到了字典键而不是字典本身的经典测试。

if item in first_lookup.keys():

应该是

if item in first_lookup:

从字典查找中获益。显式调用 first_lookup.keys() 在 Python 2 中生成一个 list,因此 in 适用于列表而不是字典。

在您的情况下,替换该循环:

for line in item_data_lol:
line = line[0]
for item in line.split():
if item in first_lookup.keys():
first_lookup[item] += 1
else:
first_lookup[item] = 1

这样会更快(使用由生成器理解初始化的 collections.Counter):

import collections
first_lookup = collections.Counter(item for line in item_data_lol for item in line[0].split())

关于Python - 将交易数据加载到列表列表中,计算每个字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41814627/

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