如何使用Python将2d-array中的列分配给一些重复的范围



我想将2d数组的列值分配给一个重复的范围。
例如,范围将从13:

[1, 0, 0]
[2, 0, 0]
[3, 0, 0]
[1, 0, 0]
[2, 0, 0]
[3, 0, 0]

我有代码:

width, height = 3, 6 
array2d = [[0 for x in range(width)] for y in range(height)]
repRange = list(range(1,4)) #it is [1, 2, 3]
j = 0
for i in range(height):    
    array2d[i][0] = repRange[j]
    if j >= len(repRange)-1:
        j = 0
    j += 1
for row in array2d:
    print(row)
输出:

[1, 0, 0]
[2, 0, 0]
[3, 0, 0]
[2, 0, 0]
[3, 0, 0]
[2, 0, 0]

它失败。开始很好,但在第二次重复时失败了。


逻辑怎么了?如果有更简单的方法,我希望你能分享。

看一下标准库模块itertools。函数cycle做你想做的:

from itertools import cycle
width, height = 3, 6 
array2d = [[0 for x in range(width)] for y in range(height)]
for l, i in zip(array2d, cycle([1,2,3])):
    l[0] = i

您的逻辑问题是,当您到达repRange的末尾时,您将j设置为1而不是0。这是因为j += 1if语句之后;if语句中的test也需要调整。这是修复后的代码。

width, height = 3, 6 
array2d = [[0 for x in range(width)] for y in range(height)]
repRange = list(range(1, 4)) #it is [1, 2, 3]
j = 0
for i in range(height):
    array2d[i][0] = repRange[j]
    j += 1
    if j >= len(repRange):
        j = 0
for row in array2d:
    print(row)

[1, 0, 0]
[2, 0, 0]
[3, 0, 0]
[1, 0, 0]
[2, 0, 0]
[3, 0, 0]

这是一个更紧凑的版本。

from itertools import cycle
width, height = 3, 6 
repRange = cycle(range(1, 4))
zeroes = [0] * (width - 1)
array2d = [[next(repRange)] + zeroes for y in range(height)]
for row in array2d:
    print(row)

这里还有一个:

from itertools import cycle
width, height = 3, 6 
zeroes = [0] * (width - 1)
array2d = [[v] + zeroes for _, v in zip(range(height), cycle(range(1, 4)))]
for row in array2d:
    print(row)

相关内容

  • 没有找到相关文章

最新更新