我需要迭代一个索引元组。所有索引必须在范围内
[0, N)
条件为 i > j
。我在这里展示的玩具示例涉及
只有两个索引;我需要将其扩展到三个(使用 i > j > k
)或更多。
基本版本是这样的:
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
我不想为每个额外的索引增加一个缩进级别, 因此我更喜欢这个版本:
for i, j in ((i, j) for i in range(N) for j in range(i)):
print(i, j)
这工作得很好,做了它应该做的并且摆脱了额外的 缩进级别。
我希望能够有更优雅的东西(对于两个索引 不是所有的相关,但对于三个或更多它变得更相关)。到目前为止我想出的是:
from itertools import combinations
for j, i in combinations(range(N), 2):
print(i, j)
这很好地迭代了同一对索引。唯一的东西是 不同的是对出现的顺序:
1 0
2 0
3 0
4 0
2 1
3 1
4 1
3 2
4 2
4 3
由于我处理这些索引的顺序是相关的,因此我不能使用它。
是否有一种优雅、简短、pythonic 的方式来按照第一个示例生成的相同顺序迭代这些索引?请记住,N
会很大,因此我不想做排序。
最佳答案
您通常可以按以下方式解决此问题:
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)]
关于python - 以 pythonic 方式使用 i > j ( > k) 迭代多个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41521725/