python - 遍历动态数量的 for 循环 (Python)

标签 python arrays for-loop numpy

我正在使用 python 对一些数字进行排序。我想创建一个函数,允许我输入一个值(4、8、16、32、64 等),创建一个数字数组,并重新排列它们的顺序。

我添加了数字,详细说明了如何确定值 = 4 和 8 的顺序。

对于 value = 4,数组 (x = [0, 1, 2, 3]) 应该被分成两部分([0,1] 和 [2,3]),然后根据每个中的第一个数字组合数组 ([0, 2 ,1 ,3])。

Figure with sequence for value = 4

对于值 = 8 的数组 (x = [0, 1, 2, 3, 4, 5, 6, 7]) 应该分成两个 ([0, 1, 2, 3] 和 [4, 5 , 6, 7]).两个数组应该再次一分为二([0, 1, 2, 3] 分为 [0,1] 和 [2,3] 和 [4, 5, 6, 7] 分为 [4,5] 和 [6, 7]).然后应根据每个数组中的第一个数字和第二组数组的顺序 ([0, 4, 2, 6, 1, 5, 3, 7]) 组合数组。

Figure for sequence for value = 8

我不知道如何处理递归(动态嵌套 for 循环)。我试图遍历通过拆分数组创建的每个分支。我研究了 itertools 和递归( Function with varying number of For Loops (python) ),但我无法让它工作。下面,我添加了代码来说明我目前的方法。

非常感谢任何帮助。我也对确定顺序的其他想法持开放态度。

我正在使用 python 2.7.6 和 numpy。

代码:

import numpy
value = 4
a = []
x = numpy.arange(value)
y = numpy.array_split(x, 2)
for i in range(2):
    for j in y:
        a.append(j.tolist()[i])
print(a)

输出:

[0, 2, 1, 3]

代码:

import numpy
value = 8
a = []
x = numpy.arange(value)
y = numpy.array_split(x, 2)
for i in range(2):
    for h in range(2):
        for j in y:
        z = numpy.array_split(j, 2)
                a.append(z[h][i])
    print(a)

输出:

[0, 4, 2, 6, 1, 5, 3, 7]

value = 16 的输出应该是 [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11 ,7 15]。

最佳答案

这是使用 np.transpose 的 NumPythonic 方法和 reshaping -

def seq_pow2(N):
    shp = 2*np.ones(np.log2(N),dtype=int)
    return np.arange(N).reshape(shp).transpose(np.arange(len(shp))[::-1]).ravel()

请注意 .transpose(np.arange(len(shp))[::-1] 将简化为 .T,因此我们将有一个简化的版本-

def seq_pow2(N):
    shp = 2*np.ones(np.log2(N),dtype=int)
    return np.arange(N).reshape(shp).T.ravel()

您可以通过ravel/flattening 来进一步简化和完全替换转置,就像在 fortran 中那样使用 .ravel('F') 最终带领我们到达 -

def seq_pow2(N):
    shp = 2*np.ones(np.log2(N),dtype=int)
    return np.arange(N).reshape(shp).ravel('F')

样本运行-

In [43]: seq_pow2(4)
Out[43]: array([0, 2, 1, 3])

In [44]: seq_pow2(8)
Out[44]: array([0, 4, 2, 6, 1, 5, 3, 7])

In [45]: seq_pow2(16)
Out[45]: array([ 0,  8,  4, 12,  2, 10,  6, 14,  1,  9,  5, 13,  3, 11,  7, 15])

关于python - 遍历动态数量的 for 循环 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36012537/

相关文章:

java - 如何每 5 秒更新一次 textview 变量

python - 使用 while 函数创建和命名文件

python使用lxml解析html表

arrays - 如何检查数组是否包含 Scala 2.8 中的特定值?

c - 多维数组断层

scala - 声明类型不同时的不同行为(Set vs TreeSet)

python - 递归代码未按预期工作 - Python 3

python - 删除 numpy 数组的对角线元素

PHP——数组中的数组?不确定,使用 ajilion MySQLidb 类需要获取原始查询的值

java - 防止 for 循环继续超出 string1 或 string2 的长度