Home > Blockchain >  New to Python and trying to find out how to gather the quantity of one specific item in a nested lis
New to Python and trying to find out how to gather the quantity of one specific item in a nested lis

Time:12-23

I'm trying to figure out a code that will go through all items of the list, and keep a count of how many times the given item occurs, without the count funtion!

This is my code:

shopping_cart= [
    ['Soap', 'Floss', 'Hand Sanitizer','Baby wipes'],
    ['Chickpeas', 'Blueberries', 'Granola'],
    ['Crayons','Construction paper','Printer ink']
]

count = 0
for [i] in shopping_cart:
    count  = len(shopping_cart)
    print(count)

CodePudding user response:

I think the easiest way to do this sort of task is to just make a dictionary, add every item to it and then you can get the count for every item.

shopping_cart = [
   ['Soap', 'Floss', 'Hand Sanitizer','Baby wipes'],
   ['Chickpeas', 'Blueberries', 'Granola'],
   ['Crayons','Construction paper','Printer ink']
]


items = {}

for row in shopping_cart:
   for item in row:
       if item not in items:
           items[item] = 0
       items[item]  = 1

print(items)

CodePudding user response:

You can do something like this if you don't want to use any built-in method:

count_items = {}
for i in shopping_cart:
    for j in i:
        if j not in d.keys():
            count_items[j] =1
        else:
            count_items[j] =1

print(count_items)

CodePudding user response:

Use Counter from collections module:

>>> Counter(item for cart in shopping_cart for item in cart)
Counter({'Soap': 1,
         'Floss': 1,
         'Hand Sanitizer': 1,
         'Baby wipes': 1,
         'Chickpeas': 1,
         'Blueberries': 1,
         'Granola': 1,
         'Crayons': 1,
         'Construction paper': 1,
         'Printer ink': 1})

OR:

items = {}
for cart in shopping_cart:
    for item in cart:
        i = items.setdefault(item, 0)
        items[item] = i   1
print(items)

# Output:
{'Soap': 1,
 'Floss': 1,
 'Hand Sanitizer': 1,
 'Baby wipes': 1,
 'Chickpeas': 1,
 'Blueberries': 1,
 'Granola': 1,
 'Crayons': 1,
 'Construction paper': 1,
 'Printer ink': 1}

CodePudding user response:

Here's a solution! It's compact but not readable or efficient :/

for items in shopping_cart:
    for item in items:
        print(item, sum([sum([1 for j in i if item == j]) for i in shopping_cart]))

CodePudding user response:

A pythonic way is to use collections.Counter and itertools.chain:

shopping_cart= [
        ['Soap', 'Floss', 'Hand Sanitizer','Baby wipes'],
        ['Chickpeas', 'Blueberries', 'Granola'],
        ['Crayons','Construction paper','Printer ink']
        ]

from collections import Counter
from itertools import chain

dict(Counter(chain.from_iterable(shopping_cart)))

Output:

{'Soap': 1,
 'Floss': 1,
 'Hand Sanitizer': 1,
 'Baby wipes': 1,
 'Chickpeas': 1,
 'Blueberries': 1,
 'Granola': 1,
 'Crayons': 1,
 'Construction paper': 1,
 'Printer ink': 1}
  • Related