user2784808
user2784808

Reputation: 23

Python List Sorting

my_list=raw_input('Please enter a list of items (separated by comma): ')
my_list=my_list.split()
my_list.sort()

print "List statistics: "

for x in my_list:
    z=my_list.count(x)

    if z>1:  
        print x, "is repeated", z, "time."
    else:
        print x, "is repeated", z, "times."

I am trying to get the program to sort the list alphabetically, then print how many of each it found. The output is:

List statistics: 
bird, is repeated 1 time.
cat, is repeated 1 time.
dog is repeated 1 time.
dog, is repeated 2 times.
dog, is repeated 2 times.

I only need it to print one time each. Also, I am trying to figure out how to put the item in quotation marks.

Upvotes: 2

Views: 256

Answers (3)

Joran Beasley
Joran Beasley

Reputation: 113930

from itertools import Counter
my_list=raw_input('Please enter a list of items (separated by comma): ')
my_list=my_list.split(",")


print "List statistics: "
import operator
for item,count in sorted(Counter(my_list).items(),key =operator.itemgetter(0)) :

    if z==1:  
        print  '"%s" is repeated %d time.'%(item,count)
    else:
        print  '"%s" is repeated %d times.'%(item,count)

if you are using python < 2.7 you can make your own counter method

def Counter(a_list):
    d = {}
    for item in a_list:
        if d.get(item,None) is None:
           d[item] = 0
        d[item] += 1
    return d

Upvotes: 3

Bleeding Fingers
Bleeding Fingers

Reputation: 7129

Replace for x in my_list: with for x in sorted(list(set(my_list))):

And though not asked in the question you could use this:

print x, "is repeated", z, "time%s." %("s" if z > 1 else "")

instead of:

if z>1:  
    print x, "is repeated", z, "time."
else:
    print x, "is repeated", z, "times."

"Pythonic" as they call it.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213203

You can iterate over a set created from list:

for x in set(my_list):
    z = my_list.count(x)

this way, you will only get each element once in the loop.

Upvotes: 1

Related Questions