Python - 将列表排序成网格

2024-04-26 18:54:23 发布

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

我正在用Python和Tkinter构建一个GUI,我需要为列表中的每个项目生成一个图形。我的单子长度从2到20不等。如何将列表排序到最有效的网格中?在

例如:

myList = [0,1,2,3,4,5,6]

len(myList)将返回7,因此最好的网格可能是3x3,最后一行有一个图形。在

像这样:Best Grid

编辑:谢谢大家的帮助。这个图形用户界面将是全屏的800x480 RaspberryPi触摸屏,所以我想在横向模式下尽可能有效地利用空间。在

到目前为止,我一直在努力:

^{pr2}$

短名单的输出似乎有效:

>>> The length of myList is: 5
>>> The integer-only root of the length of myList is: 2
>>> The remainder of the calculation is: 1

这也很管用:

myList = [1,2,3,4,5,6,7,8,9,10]

>>> The length of myList is: 10
>>> The integer-only root of the length of myList is: 3
>>> The remainder of the calculation is: 1

但当我将列表长度更改为更高的模时,它开始失败:

myList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

>>> The length of myList is: 15
>>> The integer-only root of the length of myList is: 3
>>> The remainder of the calculation is: 0

我不知道为什么这不起作用,我也不喜欢这种分类方法。有更好的方法吗?在


Tags: ofthe方法图形网格only列表is
1条回答
网友
1楼 · 发布于 2024-04-26 18:54:23

我知道为什么它不起作用了。我添加了以下几行:

length = len(myList)
rows = a
columns = c//a
remainder = c % a

print("The integer of that modulo calc is: {}".format(c//a))
print("So {} rows by {} columns can fit a list of {} with {} remaining".format(rows,columns,length,remainder))

得到了这个:

^{pr2}$

这给了我映射网格所需的所有值。如果有人知道的话,我还是愿意接受更好的方法。在

相关问题 更多 >