我有一个 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
的所有实例并获取每个 3
rd。
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 anindex
and avalue
. The list comprehension then uses thevalue
to check if it's6
and if so, returns theindex
. Those collected indexes are then sliced, beginning at the third element (index
2) with a step of 3.
通常,您可以将这一切巧妙地打包到一个函数中,该函数返回一个列表,其中包含 n
的每个 k
th 实例的索引:
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
中
n
在lst
中出现少于
k
次
在上述所有情况下,都会返回一个空列表 ([]
)。
不支持负 k
值。
关于python - 在列表中查找特定值的每三个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50559986/