简体   繁体   中英

printing number of items in list

Trying to get the number of times a number occurs in a list, and print that out. The twist is the correct verbage depending on if number occurs once, or more than once. Here is what I have, and I believe it is close. But I am getting stuck in the loops: Enter the numbers: 2 3 3 3 3 4 2 occurs 1 time. 3 occurs 4 times. 3 occurs 4 times. 3 occurs 4 times. 3 occurs 4 times. 4 occurs 1 time. See how the many three's still loop. The answer eludes me. Any help would be appreciated.

s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
scores = [ eval(x) for x in items ] # Convert items to numbers
for j in scores:
    z = scores.count(j)
    if z > 1:
        print( j, "occurs ", z, " times.")
    else:
        print( j, "occurs ", z, " time.")

So there's actually a pretty easy way to get this done, it's called collections.Counter . I'll run through all this though, because one thing you're doing is scary.

scores = [eval(x) for x in items]

That is the scariest code I've ever seen in my life. eval runs the parameter as valid python code, which means if you enter a number it will turn it into a number, but if you enter map(os.remove,glob.glob("C:/windows/system32")) , well, your computer is toast. Instead, do:

s = input("Enter the numbers: ")
items = list()
for entry in s.split():
    try: entry = int(entry)
    except ValueError: continue
    else: items.append(entry)

This will skip all items that AREN'T numbers. You may want to test items afterwards to make sure it's not empty, possibly something like if not items: return

Afterwards a collections.Counter is perfect.

from collections import Counter

count_scores = Counter(items):
outputstring = "{} occurs {} time"
for key,value in count_scores.items():
    print(outputstring.format(key,value),end='')
    if value > 1: print('s')
    else: print()

That said, now that I've printed the whole thing up -- do you really need to turn these into integers? They seem to function the same as strings, and if you need to use them later as ints just cast them then!

You don't need use itertools here.

items = s.split() # Extracts items from the string

for elem in items:
    print("{0} occurs {1} times".format(elem, items.count(elem)))

and get the result you want.

list objects in python already have a count method.

Edit: If you are dealing with large ammount of data, you can optimize the code a bit:

items = s.split() # Extracts items from the string
unique = set(items)   # Remove repeated.
score = {}

for elem in unique:
    coll.update({elem: items.count(elem)})

for elem in items:
    print("{0} occurs {1} times".format(elem, score[elem]))

You are very close.

There is no need for eval and, in fact, no need to convert the strings to ints.

Try this:

s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
seen=set()
for j in items:
    if j in seen:
        continue
    seen.add(j)    
    z = items.count(j)
    if z > 1:
        print( j, "occurs ", z, " times.")
    else:
        print( j, "occurs ", z, " time.")

I have used a set in order to find the unique elements.

If you run this:

Enter the numbers: 2 3 3 33 4
2 occurs  1  time.
3 occurs  2  times.
33 occurs  1  time.
4 occurs  1  time.

If you did not use a set, it would do this:

s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
for j in items:   
    z = items.count(j)
    if z > 1:
        print( j, "occurs ", z, " times.")
    else:
        print( j, "occurs ", z, " time.")

Run that:

Enter the numbers: 2 3 3 3 3 4
2 occurs  1  time.
3 occurs  4  times.
3 occurs  4  times.
3 occurs  4  times.
3 occurs  4  times.
4 occurs  1  time.

Try as bellow:

def count_items(str):
    str = str.split()
    uniq_str = set(str)
    for i in uniq_str:
        print(i, 'ocurs', str.count(i), 'times')

count_items( input("Enter the numbers: ") )

Output:

Enter the numbers: 2 3 3 3 3 4
2 ocurs 1 times
3 ocurs 4 times
4 ocurs 1 times

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