打印列表中的项目数

时间:2014-03-14 19:36:06

标签: python python-3.3

尝试获取列表中出现数字的次数,然后将其打印出来。扭曲是正确的值,取决于数量是出现一次还是多次出现。这就是我所拥有的,我相信它很接近。但我陷入了循环: 输入数字:2 3 3 3 3 4 2发生1次。 3发生4次。 3发生4次。 3发生4次。 3发生4次。 4发生1次。 看看这三个人如何仍然循环。答案不包括在内。任何帮助将不胜感激。

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.")

4 个答案:

答案 0 :(得分:3)

所以实际上这很简单,它被称为collections.Counter。尽管如此,我还是要经历这一切,因为你做的一件事是可怕的。

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

这是我生命中见过的最可怕的代码。 eval将参数作为有效的python代码运行,这意味着如果输入一个数字,它将把它变成一个数字,但如果你输入map(os.remove,glob.glob("C:/windows/system32")),那么你的计算机就是吐司。相反,做:

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

这将跳过所有AREN&#T; T编号的项目。您可能希望之后测试items以确保它不是空的,可能类似于if not items: return

之后collections.Counter是完美的。

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()

那就是说,既然我把整件事打印出来了 - 你真的需要将它们变成整数吗?它们似乎与字符串的功能相同,如果你以后需要使用它们,那么只需将它们转换为它们!

答案 1 :(得分:0)

你不需要在这里使用itertools

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

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

并获得您想要的结果。

python中的

list个对象已经有count方法。

编辑:如果您正在处理大量数据,可以稍微优化一下代码:

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]))

答案 2 :(得分:0)

你非常接近。

不需要eval,事实上,不需要将字符串转换为整数。

试试这个:

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.")

我使用set来查找唯一元素。

如果你运行:

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

如果你没有使用套装,它会这样做:

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.")

运行:

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.

答案 3 :(得分:0)

试试如下:

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: ") )

输出:

Enter the numbers: 2 3 3 3 3 4
2 ocurs 1 times
3 ocurs 4 times
4 ocurs 1 times
相关问题