首页 > 解决方案 > TypeError: 'dict_items' 对象在运行 if 语句以入围项目时不可下标

问题描述

我正在使用下面的函数来运行先验算法并计算所有项目集的支持度和置信度。该函数使用字典对象来存储项目的所有值及其相应的支持度和置信度。

在运行 if 语句以选择最小支持值为 0.15 且置信度为 0.6 的项目后,我在 dict_items 对象不可下标下方收到错误消息。

for key, value in largeSet.items()[1:]:

TypeError: 'dict_items' object is not subscriptable



def runApriori(data_iter, minSupport, minConfidence):
    """
    run the apriori algorithm. data_iter is a record iterator
    Return both:
     - items (tuple, support)
     - rules ((pretuple, posttuple), confidence)
    """
    itemSet, transactionList = getItemSetTransactionList(data_iter)

    freqSet = defaultdict(int)
    largeSet = dict()
    # Global dictionary which stores (key=n-itemSets,value=support)
    # which satisfy minSupport

    assocRules = dict()
    # Dictionary which stores Association Rules

    oneCSet = returnItemsWithMinSupport(itemSet,
                                        transactionList,
                                        minSupport,
                                        freqSet)

    currentLSet = oneCSet
    k = 2
    while(currentLSet != set([])):
        largeSet[k-1] = currentLSet
        currentLSet = joinSet(currentLSet, k)
        currentCSet = returnItemsWithMinSupport(currentLSet,
                                                transactionList,
                                                minSupport,
                                                freqSet)
        currentLSet = currentCSet
        k = k + 1

    def getSupport(item):
            """local function which Returns the support of an item"""
            return float(freqSet[item])/len(transactionList)

    toRetItems = []
    for key, value in largeSet.items():
        toRetItems.extend([(tuple(item), getSupport(item))
                           for item in value])

    toRetRules = []
    for key, value in largeSet.items()[1:]:
        for item in value:
            _subsets = map(frozenset, [x for x in subsets(item)])
            for element in _subsets:
                remain = item.difference(element)
                if len(remain) > 0:
                    confidence = getSupport(item)/getSupport(element)
                    if confidence >= minConfidence:
                        toRetRules.append(((tuple(element), tuple(remain)),
                                           confidence))
    return toRetItems, toRetRules

if __name__ == "__main__":
    inFile = ''
    minSupport = 0.15
    minConfidence = 0.6

    items, rules = runApriori(inFile, minSupport, minConfidence)

    printResults(items, rules) 

标签: pythonpython-3.x

解决方案


在 CPython 3.6(以及任何 Python 解释器的 3.7)之前,dicts 没有可靠的顺序,因此假设第一项是您想要跳过的项是一个主意。

也就是说,如果您使用的是 3.6+,并且您知道要跳过第一个元素,则可以使用它itertools.islice来安全地执行此操作,更改:

for key, value in largeSet.items()[1:]:

至:

# At top of file
from itertools import islice

for key, value in islice(largeSet.items(), 1, None):    

推荐阅读