这是一个有趣的解决方案,它很容易理解,并且无论列表元素的数量(奇数或偶数)如何都可以工作。
基本上,这会将列表除以2 以确定中点。然后开始遍历列表,打印第一列中点下方的每个元素,并通过将中点添加回打印的第一个元素的索引来打印中点以上的任何元素。
例如:在下面的列表l中,中点是3。所以我们遍历l,在第一列打印索引元素0,在第二列打印索引元素0+3。等等……1和1+3等等。
import math
l = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# set our break point to create the columns
bp = math.floor(len(l)/2) # math.floor, incase the list has an odd number of elements
for i,v in enumerate(l):
# break the loop if we've iterated over half the list so we don't keep printing
if i > bp:
break
# Conditions:
# 1. Only print v (currently iterated element) if the index is less-than or equal to the break point
# 2. Only print the second element if its index is found in the list
print(v if i <= bp-1 else ' ', l[i+bp] if len(l)-1 >= i+bp else ' ')
只需交换 l 和 l2 列表名称即可测试不同的列表。对于l,这将输出所需的结果:
a d
b e
c f
对于l2,会输出以下结果:
a d
b e
c f
g
希望这会有所帮助!