在列表中查找大于x的数字序列的长度

问题描述 投票:2回答:3

我想要了解序列中某些数字的基本模式,为此我需要检索序列的长度,这些数字都大于任意选择的值x(表示严重性类型)。

序列可以是例如:

list = [4, 3, 4, 5, 2, 5, 6, 5, 5, 6, 7, 6 ]

在这种情况下,场景可能是:

x=6
[1, 3] # since there are only two sequences with values greater than 6 (the 6 alone, and the triplet 6,7,6]

问题类似于:Python: determine length of sequence of equal items in list,仅适用于等数的序列。

出于这个原因,我的“草稿”是从列表的最大数量开始(在前一个场景中x = 7),然后用较低的一个替换最大数量并找到序列的长度(用6和6替换全部7)运行相同的算法以找到至少6)的长度序列。

是否有更清洁和pythonic的方式来做它?我还想不出来

python algorithm data-structures
3个回答
0
投票

使用groupby的另一种方法:

from itertools import groupby

data = [4, 3, 4, 5, 2, 5, 6, 5, 5, 6, 7, 6 ]
x = 6

out = [len(list(group)) for larger, group in groupby(elem >= x for elem in data) if larger]

此方法的工作原理是根据布尔比较elem >= x对值进行分组,然后在列表推导中记录组的长度。


1
投票

你可以使用itertools.groupby

from itertools import groupby

data = [4, 3, 4, 5, 2, 5, 6, 5, 5, 6, 7, 6 ]
x = 6

out = [sum(1 for _ in group) for is_larger, group in groupby(data, lambda value: value>=x) if is_larger]
print(out)
#[1, 3]

groupby根据条件value >= x对值进行分组,is_larger成为关键的is_larger

我们只保留Truesum(1 for _ in group)的组,对于这些组,我们用list = [0 if el < 6 else el for el in list] str = ''.join(str(el) for el in list) sequences = [seq for seq in str.split('0') if seq is not ''] lengths = [len(seq) for seq in sequences] 得到它们的长度。


0
投票

我会这样做,以使步骤更具可读性。也许不是最优雅的解决方案,但只需要基本的列表理解和字符串函数。

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.