python怎么查找序列中的数字_在python中查找数字列表的模式

该博客介绍了如何在Python中编写一个函数,用于查找序列中的众数(mode)。函数首先创建一个字典来存储序列中每个值的出现次数,然后找出出现次数最多的值。如果存在多个相同次数的众数,函数会返回所有这些众数。通过一系列示例测试了该函数,包括单值序列、等频众数序列和无众数序列。
摘要由CSDN通过智能技术生成

# 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)

co

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值