使用i>遍历多个索引j(> k)以pythonic方式 [英] Iterating over multiple indices with i > j ( > k) in a pythonic way
问题描述
我需要遍历一组索引.所有索引必须在范围内
[0, N)
,条件为i > j
.我在这里介绍的玩具示例涉及
只有两个指数;我需要将其扩展到三个(使用i > j > k
)或更多.
i need to iterate over a tuple of indices. all indices must be in the range
[0, N)
with the condition i > j
. The toy example I present here deals with
only two indices; I will need to extend that to three (with i > j > k
) or more.
基本版本是这样:
N = 5
for i in range(N):
for j in range(i):
print(i, j)
它很好用;输出是
1 0
2 0
2 1
3 0
3 1
3 2
4 0
4 1
4 2
4 3
我不想为每个其他索引增加一个缩进级别, 因此我更喜欢这个版本:
I don't want to have one more indentation level for every additional index, therefore I prefer this version:
for i, j in ((i, j) for i in range(N) for j in range(i)):
print(i, j)
这很好地工作了,做了应该做的事,摆脱了多余的东西 缩进级别.
this works perfectly well, does what it should and gets rid of the extra indentation level.
我希望能够拥有一些更优雅的东西(对于两个索引 并不是所有相关的内容,而是三个或三个以上的内容就变得更加相关).到目前为止,我想到的是:
I was hoping to be able to have something more elegant (for two indices that is not all that relevant, but for three or more it becomes more relevant). What I came up with so far is this:
from itertools import combinations
for j, i in combinations(range(N), 2):
print(i, j)
这很好地遍历了同一对索引.唯一的是 配对出现的顺序不同:
This iterates over the same pair of indices just fine. The only thing that is different is the order in which the pairs appear:
1 0
2 0
3 0
4 0
2 1
3 1
4 1
3 2
4 2
4 3
由于我处理这些索引的顺序是相关的,因此我不能使用它.
As the order of what I am doing with these indices is relevant, I therefore cannot use this.
是否有一种优雅,简短,Python式的方式以第一个示例产生的顺序迭代这些索引?请记住,N
会很大,所以排序不是我想要做的.
Is there an elegant, short, pythonic way to iterate over these indices in the same order that the very first example produces? Keep in mind that N
will be large, so sorting is not something I would want to do.
推荐答案
您通常可以如下解决此问题:
You could solve this generally as follows:
def indices(N, length=1):
"""Generate [length]-tuples of indices.
Each tuple t = (i, j, ..., [x]) satisfies the conditions
len(t) == length, 0 <= i < N and i > j > ... > [x].
Arguments:
N (int): The limit of the first index in each tuple.
length (int, optional): The length of each tuple (defaults to 1).
Yields:
tuple: The next tuple of indices.
"""
if length == 1:
for x in range(N):
yield (x,)
else:
for x in range(1, N):
for t in indices(x, length - 1):
yield (x,) + t
使用中:
>>> list(indices(5, 2))
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3)]
>>> list(indices(5, 3))
[(2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1), (4, 1, 0), (4, 2, 0), (4, 2, 1), (4, 3, 0), (4, 3, 1), (4, 3, 2)]
这篇关于使用i>遍历多个索引j(> k)以pythonic方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!