简体   繁体   中英

Limitless count for occurrences in a list

I have a piece of code designed to analyse multiple files in a directory and output various details upon request. I'm trying to figure out how to implement a histogram like system to display this data.

Currently my output looks like this..

Metric of interest? lines_of_code
lines_of_code        8
lines_of_code        23

When I'm trying to achieve this result..

Metric of interest? lines_of_code

Bin range    Count
0-9            1
20-29          1

How would I go about doing this? From what I've seen, most people feel as if importing counter from collections is the way to go.

This is what that segment of code looks like..

elif metric_choice == 'lines_of_code':
    for files in os.listdir("."):
        if files.endswith(".py"):
            file_open = open(files, "r")
            file_contents = file_open.readlines()
            print("{0:20} {1}".format("lines_of_code", (len(file_contents))))

Cheers!

import glob
import collections

counter = collections.Counter()
for py_filename in glob.glob('*.py'):
    with open(py_filename) as f:
        linecount = sum(1 for line in f)
    counter[linecount//10] += 1

for i,n in sorted(counter.items()):
    print('{}-{}: {}'.format(i * 10, (i + 1) * 10 - 1, n))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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