输出列表中的项目数量
我想要计算一个数字在列表中出现的次数,并把结果打印出来。这里有个小问题,就是要根据数字出现的次数来选择正确的说法:如果只出现一次,就说“1次”,如果出现多次,就说“多次”。我现在的代码差不多可以了,但在循环的部分遇到了麻烦:
输入的数字是:2 3 3 3 3 4
结果显示:2出现了1次。
3出现了4次。
3出现了4次。
3出现了4次。
3出现了4次。
4出现了1次。
你看,数字3的结果重复了很多次。我就是搞不清楚问题出在哪里。希望能得到一些帮助。
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 个回答
试试下面的代码:
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
你已经很接近了。
其实不需要用到 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.")
我使用了一个 集合 来找出唯一的元素。
如果你运行这个:
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.
这里其实不需要用到 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]))
其实有个很简单的方法可以解决这个问题,叫做 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)
这样做会跳过所有不是数字的项。你可能还想在之后检查一下 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()
话说回来,现在我把整个事情都说完了——你真的需要把这些转换成整数吗?它们似乎和字符串的功能是一样的,如果你之后需要用到它们作为整数,只需在那时转换就可以了!