Skip to content
Advertisement

Histogram of lists enteries

I have a number of lists as follows:

list1 = ['a_1','a_2','b_17','c_19']
list2 = ['aa_1','a_12','b_15','d_39']
list3 = ['a_1','a_200','ba_1','u_0']

I wish to generate a histogram based on the labels, ignoring the numbering, that is, a has 4 entries over all the lists, ba 1 entry, u has 1 entry, and so on. The labels, are file names from a specific folder, before adding the numbers, so it is a finite known list.

How can I perform such a count without a bunch of ugly loops? Can I use unique here, somehow?

Advertisement

Answer

You cannot acheive it without a loop. But you can instead use list comphrension to make it into a single line. Something like this.

list1 = ['a_1','a_2','b_17','c_19']
list2 = ['aa_1','a_12','b_15','d_39']
list3 = ['a_1','a_200','ba_1','u_0']

lst = [x.split('_')[0] for x in (list1 + list2 + list3)]

print({x: lst.count(x) for x in lst})
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement