2
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.

1
  • 1
    str.split with no argument splits on whitespace, not commas. Commented Sep 16, 2013 at 18:23

3 Answers 3

3
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
Sign up to request clarification or add additional context in comments.

3 Comments

-1: OP mentioned that I am trying to get the program to sort the list alphabetically. I wonder, using COunter, how can you print it in alphabetic order. Also your program has lot of syntax errors.
Using split() on a string with comma separated items will lead to wrong results.
I just copied and pasted his code for the split ... i just added the counter part ... anyway fixed the split and the alphabetical thing ...
1

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.

Comments

0

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.

2 Comments

When I add that second line it only prints one of the items in the list such as "dog", but it will not print for all of the variables bird, cat, dog. Thanks for the help!
@user2784808 did you add it within the loop? indentations checked? btw answer updated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.