我是靠谱客的博主 瘦瘦乌龟,这篇文章主要介绍python怎么查找序列中的数字_在python中查找数字列表的模式,现在分享给大家,希望可以做个参考。

# 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怎么查找序列中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部