遍历列表

时间:2019-05-27 20:52:40

标签: python list

事务csv看起来像这样,我将它们添加到列表中,如下所示。

Bread Milk

Bread Diapers Beer Eggs Beer


[{'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Diapers': 1, 'Beer': 6, 'Eggs': 1}, {'Milk': 1, 'Diapers': 1, 'Beer': 6, 'Cola': 1}, {'Bread': 1, 'Milk': 1, 'Diapers': 1, 'Beer': 6}, {'Bread': 1, 'Milk': 1, 'Diapers': 2, 'Cola': 1, 'Chips': 2, 'Beer': 1, '': 1}, {'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}, {'Milk': 1, 'Bread': 1, 'Beer': 4, 'Cola': 1, 'Diapers': 1, 'Chips': 1}, {'Bread': 1, 'Milk': 2, 'Diapers': 2, 'Beer': 2, 'Chips': 2}, {'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}]

我只考虑包含3个尿布的列表。

我希望交易仅返回如下所示:

{'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}
{'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}


{'Bread', 'Beer', 'Diapers', 'Milk'}
{'Bread', 'Cola', 'Beer', 'Milk', 'Chips', 'Diapers', ''}

我的代码是:

def M():
    li = []
    # Open the csv file
    with open('transaction.csv') as fp:
        DataCaptured = csv.reader(fp, delimiter=',')
        # Iterate through each word in csv and add it's counter to the row
        for row in DataCaptured:
            li.append(dict(Counter(row)))
            if li['Diaper']==3: ---> I am missing this logic not sure how to get it.

    # Return the list of counters
        return li



print(M())

1 个答案:

答案 0 :(得分:0)

li=[{'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Diapers': 1, 'Beer': 6, 'Eggs': 1}, {'Milk': 1, 'Diapers': 1, 'Beer': 6, 'Cola': 1}, {'Bread': 1, 'Milk': 1, 'Diapers': 1, 'Beer': 6}, {'Bread': 1, 'Milk': 1, 'Diapers': 2, 'Cola': 1, 'Chips': 2, 'Beer': 1, '': 1}, {'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}, {'Milk': 1, 'Bread': 1, 'Beer': 4, 'Cola': 1, 'Diapers': 1, 'Chips': 1}, {'Bread': 1, 'Milk': 2, 'Diapers': 2, 'Beer': 2, 'Chips': 2}, {'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}]
    for d in li:
        if 'Diapers' in d and d['Diapers']==3:
            print(d)

输出:

{'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}
{'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}