概述
# Function to return all modes, this function takes into account multimodal distributions.
# Function returns all modes as list or 'NA' if such value doesn't exist.
def mode(l):
if len(l) > 1: #
#Creates dictionary of values in l and their count
d = {}
for value in l:
if value not in d:
d[value] = 1
else:
d[value] += 1
if len(d) == 1:
return [value]
else:
# Finds most common value
i = 0
for value in d:
if i < d[value]:
i = d[value]
# All values with greatest number of occurrences can be a mode if:
# other values with less number of occurrences exist
modes = []
counter = 0
for value in d:
if d[value] == i:
mode = (value, i)
modes.append(mode)
counter += mode[1] # Create the counter that sums the number of most common occurrences
# Example [1, 2, 2, 3, 3]
# 2 appears twice, 3 appears twice, [2, 3] are a mode
# because sum of counter for them: 2+2 != 5
if counter != len(l):
return [mode[0] for mode in modes]
else:
return 'NA'
else:
return l
l1 = [1]
l2 = [1, 1]
l3 = [1, 1, 2, 2]
l4 = [1, 2, 3, 4, 5]
l5 = [1, 1, 2, 2, 3, 3, 4]
l6 = [1, 2, 3, 4, 4]
l7 = ['string', 'string', 1]
l8 = ['string', 'string', 1, 1, 1]
print mode(l1)
print mode(l2)
print mode(l3)
print mode(l4)
print mode(l5)
print mode(l6)
print mode(l7)
print mode(l8)
最后
以上就是瘦瘦乌龟为你收集整理的python怎么查找序列中的数字_在python中查找数字列表的模式的全部内容,希望文章能够帮你解决python怎么查找序列中的数字_在python中查找数字列表的模式所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复