首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:在查找列表中最小数的最长序列长度时,输出不正确

Python:在查找列表中最小数的最长序列长度时,输出不正确
EN

Stack Overflow用户
提问于 2018-11-18 12:23:43
回答 4查看 102关注 0票数 2

我试图在列表中找到最小数的最长序列。例如,对于这个列表,resp_rates = [1,1,2,89,56,4,1,1,1,1,10,5,67,1,1,1,76,5,7,6,6,6,1,1,1,1,1,1,1],最小数为1,1的序列长度分别为,2,4,3,7。因此,最长序列的长度是7,但是,我的代码打印4。

代码:

代码语言:javascript
复制
resp_rates = [1,1,2,89,56,4,1,1,1,1,10,5,67,1,1,1,76,5,7,6,6,6,1,1,1,1,1,1,1]
rr_min_current = np.amin(resp_rates)
print(rr_min_current)
count = 0
first = 1
min_rr_sequence = []
print(resp_rates)
for resp_rate in resp_rates:
    if resp_rate == rr_min_current and first == 1:
        count=count+1 
        first = 0
    elif resp_rate == rr_min_current and first == 0:
        count=count+1
    elif resp_rate != rr_min_current and first == 0:    
        min_rr_sequence.append(count)
        first = 1
        count = 0
#longest_min_rr_sequence.append(np.amax(min_rr_sequence))
print(min_rr_sequence)
longest_min_rr_sequence = np.amax(min_rr_sequence)
print(longest_min_rr_sequence)

输出:

代码语言:javascript
复制
1
[1, 1, 2, 89, 56, 4, 1, 1, 1, 1, 10, 5, 67, 1, 1, 1, 76, 5, 7, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1]
[2, 4, 3]
4
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-11-18 12:36:04

给您(编辑):

代码语言:javascript
复制
resp_rates = [1,1,1,1,1,1,1,1,1,1,1,2,89,56,4,1,1,1,1,10,5,67,1,1,1,76,5,7,6,6,6,1,1,1,1,1,1,1]

lowest = resp_rates[0]
count = 0
max_count = 0

for i in resp_rates:
    if i < lowest:
        lowest = i
        count = 1
        max_count = count
    elif i == lowest:
        count = count + 1
        if count > max_count:
            max_count = count
    else:
        count = 0


print(max_count)
票数 1
EN

Stack Overflow用户

发布于 2018-11-18 12:28:13

使用groupby的简短解决方案

代码语言:javascript
复制
from itertools import groupby

resp_rates = [1,1,2,89,56,4,1,1,1,1,10,5,67,1,1,1,76,5,7,6,6,6,1,1,1,1,1,1,1]

out = -min((value, -len(list(group))) for value, group in groupby(resp_rates))[1]
print(out)
# 7

一些解释:(value, -len(list(group))) for value, group in groupby(resp_rates))生成元组:(1, -2), (2, -1), (89, -1), ... (1, -4) ...

min将返回具有最小值的元组,如果许多元组具有相同的最小值,则返回长度最大的元组(因此可以使用-length来实现最小值)。

我们只需要保持长度远离最小的元组,并改变它的符号。

票数 2
EN

Stack Overflow用户

发布于 2018-11-18 12:29:29

这样做:

代码语言:javascript
复制
In [72]: resp_rates = [1,1,2,89,56,4,1,1,1,1,10,5,67,1,1,1,76,5,7,6,6,6,1,1,1,1,1,1,1]

In [73]: import itertools,operator
In [83]: r = max((list(y) for (x,y) in itertools.groupby((enumerate(resp_rates)),operator.itemgetter(1)) if x == min(resp_rates)), key=len)

In [84]: len(r)
Out[84]: 7
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53360831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档