gpt4 book ai didi

python - 在列表中查找特定值的每三个实例

转载 作者:行者123 更新时间:2023-11-28 20:14:19 36 4
gpt4 key购买 nike

我有一个 python 列表,其中包含数百个整数,范围从 1 到 6(含)。本质上,我想创建一个函数来查找 6 的每三个实例的索引。考虑这个例子:

l = [5, 2, 2, 1, 4, 5, 4, 6, 6, 5, 5, 3, 3, 2, 1, 3, 5, 3, 5, 2, 4, 4, 2, 3, 3, 2, 6, 2, 3, 6, 3, 6, 1, 6]

6_finder(l)
> [26, 33]

在此示例中,6 的第三个实例出现在索引 26 处,下一个 6 的第三个实例出现在索引 33 处。

关于如何处理这个问题的任何提示?我的直觉告诉我嵌套循环可能是必要的。任何帮助,将不胜感激。

最佳答案

找到 6 的所有实例并获取每个 3rd

l = [5, 2, 2, 1, 4, 5, 4, 6, 6, 5, 5, 3, 3, 2, 1, 3, 5, 3, 5, 2, 4, 4, 2, 3, 3, 2, 6, 2, 3, 6, 3, 6, 1, 6]

res = [i for i, x in enumerate(l) if x == 6][2::3]
print(res)

打印

[26, 33]

Explanation@BrettBeatty:

Iterating over enumerate yields both an index and a value. The list comprehension then uses the value to check if it's 6 and if so, returns the index. Those collected indexes are then sliced, beginning at the third element (index 2) with a step of 3.


通常,您可以将这一切巧妙地打包到一个函数中,该函数返回一个列表,其中包含 n 的每个 kth 实例的索引:

def get_index_of_kth_n(lst, n, k=1):
return [i for i, x in enumerate(lst) if x == n][k-1::k]

它还处理极端情况,例如:

  • lst 传递的是空
  • n 没有出现在 lst
  • nlst
  • 中出现少于 k

在上述所有情况下,都会返回一个空列表 ([])。不支持负 k 值。

关于python - 在列表中查找特定值的每三个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50559986/

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