>新手到Python。我想知道如何在六边形网格中存储字母。我尝试使用图形,但我不太了解它。第一个字母(来自文件或其他东西)进入蜂窝结构的中心六边形框,下一组字母(6)将填充在其外部,依此类推。谢谢。
If the letters are ['a', 'b', 'c', 'd', 'e', 'f', 'g'], then a goes to the center hex and b to g fill in the outside hex grids in clockwise direction.
更清楚地说,字母是从A到S。目的是将其存储在六边形蜂窝结构中,中心有a,(b,c,d,e,f,g)在它外面,(h,i,j,k,l,m,n,o,p,q,r,s)在它外面,依此类推。
很难理解你所说的"六边形网格"是什么意思。但无论如何,这是一个解决方案的尝试。编辑:好的,你想要的现在更清楚了。以下解决方案应该有效。
我假设您希望将数据保存在某种表示几何六边形网格的数据结构中。六边形网格由一个由 6 个六边形包围的单个中央六边形组成,这些六边形又被 12 个六边形包围,然后是 18 个,依此类推。
我们可以使用列表列表来表示这种几何结构:
[['a'], ['b','c','d','e','f','g'], ['h','i','j','k','l','m','n','o','p','q','r','s']]
第一个列表的长度为 1,第二个列表的长度为 6,依此类推。您可以通过这种方式访问蜂窝的每个"级别",然后访问该级别的字母(请注意,索引以零开头,而不是 1):
my_honeycomb[0][0] # 'a'
my_honeycomb[2][3] # 'k'
my_honeycomb[1][7] # IndexError
第三条语句生成索引错误,因为对于该级别,索引 7 不存在。
加载蜂窝结构的一种方法是使用 input()
函数:
my_honeycomb = [[]] # a list containing an empty list
level = 0
ind = 0
for letter in input('Enter your string:nnt'):
if ind > level * 6: # check if index is valid for this level
level += 1
ind = 1
my_honeycomb.append([]) # go to the next level
my_honeycomb[level].append(letter) # add letter to current level
ind += 1 # advance to next index