例如说我有这个名单:如何将一个列表分成两个列?
list = ["a", "b", "c", "d", "e", "f"]
我需要为了做它被打印到shell这样的:
a d
b e
c f
任何想法?
例如说我有这个名单:如何将一个列表分成两个列?
list = ["a", "b", "c", "d", "e", "f"]
我需要为了做它被打印到shell这样的:
a d
b e
c f
任何想法?
这里有一个有趣的解决方案,是很容易理解的,并且具有不管列表元素的数量(奇数或偶数)的工作的好处。
基本上,这会将列表除以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
希望这有助于!
快速回答:
list = ["a", "b", "c", "d", "e", "f"]
newList = []
secList = []
if len(list)%1 == 0: ###will only work is list has even number of elements
for i in range(len(list)):
if i < len(list)/2:
newList.append(list[i])
else:
secList.append(list[i])
for i,j in zip(newList, secList):
print i,j
@Mitch不,那是一个错误,我还没有完成编辑它。 –
为什么不分成2个列表然后打印它们? – Juergen
似乎对我来说是一个合法的问题,不知道为什么它被低估了。 +1 – sadmicrowave