How do I split up a list into two colums?

◇◆丶佛笑我妖孽 提交于 2019-12-13 03:35:08

问题


Say for example I had this list:

list = ["a", "b", "c", "d", "e", "f"]

What would I need to do in order for it to be printed to the shell like this:

a    d
b    e
c    f

Any ideas?


回答1:


Here is an interesting solution that is pretty easy to understand, and has the added benefit of working regardless of the number of list elements (odd or even).

Basically, this will divide the list by 2 to determine the mid-point. Then begin iterating through the list, printing each element below the mid-point in the first column, and printing any element above the mid-point by adding the mid-point back to the index of the first element that was printed.

For example: in list l below, the mid-point is 3. So we iterate over l and print index element 0 in the first column, and print index element 0+3 in the second column. And so-on... 1 and 1+3, etc.

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 ' ')

Just swap the l and l2 list names to test the different lists. For l, this will output the desired results of:

a   d
b   e
c   f

And for l2 will output the results of:

a   d
b   e
c   f
    g

Hope this helps!




回答2:


Quick answer:

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


来源:https://stackoverflow.com/questions/46571381/how-do-i-split-up-a-list-into-two-colums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!