如何使用Python定义将2D数组分割为多少部分?

2024-09-28 21:10:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的数据结构:

enter image description here

这是一个二维数组,分为3个部分。对于数组中的每个字母,我需要定义编号。例如,字母a,b,c,d第1节中;e,f,g,h第2节中。你知道吗


我的密码。首先,2d阵列准备:

from itertools import cycle
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

#2d-array initialization  
width, height = 3, 6 
repRange = cycle(range(1, 3))
values = [0] * (width - 1)
array2d = [[next(repRange)] + values for y in range(height)]

#Filling array with letters:
m = 0
for i in range(height):
    for j in range(1,width):
       array2d[i][j] = letters[m] 
       m+=1

#Printing:      
for row in array2d:
    print(row)

输出:

[1, 'a', 'b']
[2, 'c', 'd']
[1, 'e', 'f']
[2, 'g', 'h']
[1, 'i', 'j']
[2, 'k', 'l']

现在我需要确定每个字母的节号,并将其与字母本身一起保存。我使用defineSection函数并将值保存在字典中:

def defineSection(i, division, height):
    if i <= division:
        return 1
    elif division*2 >= i > division :
        return 2
    elif division*3 >= i > division*2 :
        return 3   

dic = {}
for i in range(height):
    for j in range(1,width):
        section = defineSection(i+1, 2, height)
        dic.update({array2d[i][j] : section})

for item in dic.items():
    print(item)

输出:

('f', 2)
('b', 1)
('c', 1)
('e', 2)
('k', 3)
('g', 2)
('d', 1)
('a', 1)
('l', 3)
('h', 2)
('i', 3)
('j', 3)

它正确地定义了每个字母的所有节号。但是defineSection方法是原始的,如果行数大于6,它将不起作用。 我不知道如何实现defineSection方法,以便它自动定义节号,只考虑当前的行数除法行数。你知道吗


问题:有没有什么方法可以不用那么多if-elif条件,独立于行总数,直接确定节数?你知道吗


Tags: inforreturn定义字母rangewidthdivision
1条回答
网友
1楼 · 发布于 2024-09-28 21:10:24

您可以大大简化矩阵创建代码。您只需要一个letters迭代器,它返回自身,这样您就可以使用zip一次迭代两个字母。你知道吗

In [3]: from itertools import cycle

In [4]: letters = "abcdefghijkl"

In [5]: ranges = cycle(range(1,3))

In [6]: iter_letters = iter(letters)

In [7]: matrix = [[i,a,b] for i,a,b in zip(ranges,iter_letters,iter_letters)]

In [8]: matrix
Out[8]: 
[[1, 'a', 'b'],
 [2, 'c', 'd'],
 [1, 'e', 'f'],
 [2, 'g', 'h'],
 [1, 'i', 'j'],
 [2, 'k', 'l']]

至于分配分区,请注意每两行有一个分区,即四个字母,因此可以使用简单的楼层划分来“跳过”计数。你知道吗

In [9]: sections = {letter:(i//4 + 1) for i,letter in enumerate(letters)}

In [10]: sections
Out[10]: 
{'a': 1,
 'b': 1,
 'c': 1,
 'd': 1,
 'e': 2,
 'f': 2,
 'g': 2,
 'h': 2,
 'i': 3,
 'j': 3,
 'k': 3,
 'l': 3}

相关问题 更多 >