1

I have a list like this:

dttrain = [["sunny","hot","high","false","no"],
    ["sunny","hot","high","true","no"],
    ["overcast","hot","high","false","yes"]]

I want to count the frequency by the last index, so for example:

sunnny no = 2 , sunny yes = 0, hot no = 2, hot yes = 1.

I have tried my own code:

c = Counter(x for sublist in dttrain for x in sublist)

But this shows:

Counter({'yes': 9, 'false': 8, 'high': 7, 'normal': 7, 'true': 6, 'mild': 6, 'sunny': 5, 'no': 5, 'rainy': 5, 'hot': 4,'overcast': 4, 'cool': 4})
2
  • What should it show instead? Commented Nov 4, 2017 at 16:52
  • 1
    sunnny no = 2 , sunny yes = 0, hot no = 2, hot yes = 1 -> like this sir, Commented Nov 4, 2017 at 16:54

2 Answers 2

2

Here is some untidy code:

def iterate_key(name, _counter):
    """
    Iterate a key in a dict, create key if it doesn't exist.

    :param str name: Name of key to iterate.
    :param dict[int] _counter: Dictionary storing count data.
    :return: _counter after iterating key.
    """
    if name not in counter:
        _counter[name] = 1
    else:
        _counter[name] += 1
    return _counter


counter = {}
for sub_list in dttrain:
    key_name = '{}_{}'.format(sub_list[0], sub_list[-1])
    counter = iterate_key(key_name, counter)

    key_name = '{}_{}'.format(sub_list[1], sub_list[-1])
    counter = iterate_key(key_name, counter)

print(counter)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you so much sir, you save my time. Thanks again. Wassalamualaikum.
1

Use the combination of itertools(product and chain) and collections.Counter

from itertools import product, chain
from collections import Counter
{' '.join(k):v for k,v in Counter(chain(*[product(i[:2],[i[-1]]) for i in dttrain])).items()}

Output:

{'hot no': 2, 'hot yes': 1, 'overcast yes': 1, 'sunny no': 2}

4 Comments

Oh thank again sir, its simple, but can i get the element from the counter?
@Fian Eka - Please see my Edit
what a nice code sir, love this. thanks again sir. Wassalamualaikum
Ye, my hack is pretty convoluted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.