python - 以 pythonic 方式使用 i > j ( > k) 迭代多个索引

标签 python python-3.x python-itertools

我需要迭代一个索引元组。所有索引必须在范围内 [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/

相关文章:

python - pygresql - 插入和返回串行

python - 如何设置颜色条中间最低值的连续正颜色条范围

python - 带有 Eager 模式的 TF.data.dataset.map(map_func)

python - 如何连接固定两个枢轴的列表的元素?

python - 如何检查列表中是否存在子序列?

python:是否有用于分块输入流的库函数?

python - 使用 python 将 dict 值分组为 block

python - Qt 未在远程桌面上加载(无法初始化 XRandr)

python - 如何在 tkinter python 中的按钮小部件的命令属性中使用 lambda 表达式调用回调函数

python-3.x - Docker 容器总是显示 ssl 连接错误