我有这样的数据结构:
这是一个二维数组,分为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
条件,独立于行总数,直接确定节数?你知道吗
您可以大大简化矩阵创建代码。您只需要一个
letters
迭代器,它返回自身,这样您就可以使用zip一次迭代两个字母。你知道吗至于分配分区,请注意每两行有一个分区,即四个字母,因此可以使用简单的楼层划分来“跳过”计数。你知道吗
相关问题 更多 >
编程相关推荐