gpt4 book ai didi

python - 从列表中提取数字

转载 作者:太空狗 更新时间:2023-10-30 01:00:13 26 4
gpt4 key购买 nike

我创建了一个列表(已排序):

indexlist = [0, 7, 8, 12, 19, 25, 26, 27, 29, 30, 31, 33]

我想从这个列表中提取至少相距五个的数字,并将它们输入到另一个列表中。这有点令人困惑。这是我想要输出的示例:

outlist = [0, 7, 19, 25, 31]

如您所见,没有一个数字彼此相差在 5 以内。

我试过这个方法:

for index2 in range(0, len(indexlist) - 1):
if indexlist[index2 + 1] > indexlist[index2] + 5:
outlist.append(indexlist[index2])

但是,这给了我这个输出:

outlist = [0, 12, 19]

当然,数字至少相差 5,但是,我缺少一些需要的值。

关于如何完成这项任务有什么想法吗?

最佳答案

您需要跟踪添加到列表中的最后一项,而不仅仅是与以下值进行比较:

In [1]: indexlist = [0, 7, 8, 12, 19, 25, 26, 27, 29, 30, 31, 33]
In [2]: last = -1000 # starting value hopefully low enough :)
In [3]: resultlist = []
In [4]: for item in indexlist:
...: if item > last+5:
...: resultlist.append(item)
...: last = item
...:
In [5]: resultlist
Out[5]: [0, 7, 19, 25, 31]

关于python - 从列表中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36772065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com