>假设我有一个像 [0 0 0 0] 这样的数组,我想以类似基础的规模迭代它。假设我选择基数 100,并假设我想在一个小端系统中执行此操作。我的输出如下所示:
[1 0 0 0]
[2 0 0 0]
...
[99 0 0 0]
[0 1 0 0]
我的代码目前在函数"indexArray"中,但我想知道是否可以在没有 if 语句的情况下以更简单的方式做到这一点?
def indexArray(enteredArr):
enteredArr[0] += 1
for i in range(len(enteredArr)):
if enteredArr[i] > 99:
enteredArr[i] = 0
enteredArr[i + 1] += 1
return enteredArr
像往常一样,在Python中,如果你寻找它,有一种更简单的方法。
您的主循环可能是:
for i in itertools.product(range(BASE), repeat=NDIM):
... stuff ...
对于示例,BASE=100 和 NDIM=4,但相同的方法适用于任何其他值。
i
将是一个数组值的元组,像(0, 0, 0, 0), (0, 0, 0, 1) ... (BASE-1, BASE-1, BASE-1, BASE-1)
一样计数。
num = 45
base = 3
num_base = []
remainder = num
# the remainders of the integer divisions of the number by the base are the digits of the number in the new base
# see also here: https://math.stackexchange.com/questions/111150/changing-a-number-between-arbitrary-bases
while remainder:
num_base.append(remainder % base)
remainder //= base
# join the list in reverse while changing type of digits to characters
print("".join(str(x) for x in num_base[::-1]))