python双索引怎么引用,使用i>遍历多个索引j(> k)以Python方式

本文探讨如何使用Python高效且简洁地生成满足i>j条件的多维索引,避免额外缩进。作者提供了一种通用函数`indices`,通过迭代和组合生成指定长度的索引元组,适用于不同维度的索引需求,如(i,j,k)等,同时保持与基础示例相同的顺序输出。
摘要由CSDN通过智能技术生成

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.

The basic version is this:

N = 5

for i in range(N):

for j in range(i):

print(i, j)

and it works just fine; the output is

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.

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

In use:

>>> 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)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值