我想创建一个打印出现最多数字的函数,但我在标题上有问题,这是我的功能:
def most_appear_q3(word):
most = 0
for num in word:
num_checked= num
if(word.count(num)>= most):
most = word.count(num)
else:
del word[num_checked]
print [most + word]
most_appear_q3([1,2,2,2,3,4,5,5,5,6])
这是错误:
print [most + word]
TypeError: unsupported operand type(s) for +: 'int' and 'list'
结果需要为3,[2,5]因为2和5出现3次
答案 0 :(得分:1)
您不必从列表中删除项目,以便最后过滤列表中出现次数最多的项目,只需迭代它并保留变量中的最大计数值并存储元素然后,列表中的最大计数返回最大计数和列表,这样:
def most_appear_q3(word):
most = 0
most_comm = []
for num in word:
#num_checked= num - No need for this line
c = word.count(num)
if(c == most) and num not in most_comm: #To avoid Duplicate items
most_comm.append(num)# Found an element with same max counting
elif (c > most):
most = c #New Max Count Found
most_comm = [] #delete all previous elements
most_comm.append(num)
return most, most_comm
>>>print most_appear_q3([1,2,2,2,3,4,5,5,5,6]) #or print (most_appear_q3([1,2,2,2,3,4,5,5,5,6])) if you are using Python 3+
(3, [2, 5])
另一种方法是使用内置方法,例如max
,key
是每个项目的count
,这样:
>>> l = [1,2,2,2,3,4,5,5,5,6]
>>> max(l, key=lambda s:l.count(s))
2
答案 1 :(得分:0)
You have done some minor mistakes like:
1. It will not check the first number.
2. Print should be out side the loop
3. you have already mentioned.
To fix the error mentioned by you, you have need to change
the print statement.
def most_appear_q3(word):
most = 0
for num in word:
num_checked= num
if(word.count(num)>= most):
most = word.count(num)
else:
del word[num_checked]
print (str(most) + str(word))
most_appear_q3([1,2,2,2,3,4,5,5,5,6])
Result:
>>>
1[1, 2, 2, 2, 3, 4, 5, 5, 5, 6]
3[1, 2, 2, 2, 3, 4, 5, 5, 5, 6]
3[1, 2, 2, 2, 3, 4, 5, 5, 5, 6]
3[1, 2, 2, 2, 3, 4, 5, 5, 5, 6]
3[1, 2, 2, 3, 4, 5, 5, 5, 6]
3[1, 2, 2, 3, 4, 5, 5, 5, 6]
3[1, 2, 2, 3, 4, 5, 5, 5, 6]
3[1, 2, 2, 3, 4, 5, 5, 5, 6]
3[1, 2, 2, 3, 4, 5, 5, 6]
>>>
I think this is not what you expected, so modifying the code.
May be this will help you.
def filter_least_appeared(word, count, num):
if(word.count(num)>= count):
count = word.count(num)
else:
word[:] = filter(lambda val: val != num, word)
return word, count
def most_appear_q3(word):
count = 0
""" This will not check the first number."""
for num in set(word):
word, count = filter_least_appeared(word, count, num)
"""Check for first number."""
word, count = filter_least_appeared(word, count, list(set(word))[0])
print (str(count) + ',' + str(list(set(word))))
most_appear_q3([1,2,2,2,3,4,5,5,5,6])
>>>
3,[2, 5]
>>>