2 回答
TA贡献1831条经验 获得超4个赞
创建一个compute_mode带有接受列表的参数的函数(在本例中为num_count)。该函数查找模式并将其存储在中temp_list,然后将其打印出来
将所有模式值附加到这样的列表中:
temp_list.append(num)
然后像这样打印列表:
print("Mode: " ,temp_list)
最终代码:
temp_list = []
def compute_mode(my_list):
counts = {}
maxcount = 0
for number in my_list:
if number not in counts:
counts[number] = 0
counts[number] += 1
if counts[number] > maxcount:
maxcount = counts[number]
for number, count in counts.items():
if count == maxcount:
temp_list.append(number)
num_count = [1,2,3,4,1,2,3,4,4] #any list
compute_mode(num_count)
print('Mode:', temp_list)
TA贡献1828条经验 获得超4个赞
使用清单
maximum = 0
modes = []
for num in num_count:
count = num_count[num]
if count > maximum:
maximum = count
if count == maximum:
modes.append(num)
print('Mode: ', modes)
添加回答
举报