繁体   English   中英

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

[英]Python - load transaction data into a list of lists, count occurrence of each string

由于要执行作业,因此我重新使用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

其中每个字母对应于购买特定产品,并且每一行都是一笔交易(对于第一行,有人购买了产品ABCDE和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函数加快代码的这一部分(我主要用于循环,并且由于我对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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM