如何将列表分成两个列? [英] How do I split up a list into two colums?

查看:128
本文介绍了如何将列表分成两个列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有此列表:

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

要像这样将其打印到外壳上,我需要做些什么:

a    d
b    e
c    f

有什么想法吗?

解决方案

这是一个有趣的解决方案,非常易于理解,并且无论列表元素的数量(奇数或偶数)如何,都具有工作的附加好处. /p>

基本上,这会将列表除以2来确定中点.然后开始遍历该列表,在第一列的中点下方打印每个元素,然后通过将中点添加回已打印的第一个元素的索引中,在中点上方打印任何元素.

例如:在下面的列表l中,中点是3.因此,我们遍历l并在第一列中打印索引元素0,并在第二列中打印索引元素0+3.等等... 11+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 ' ')

只需交换ll2列表名称即可测试不同的列表.对于l,这将输出所需的结果:

a   d
b   e
c   f

对于l2,将输出以下结果:

a   d
b   e
c   f
    g

希望这会有所帮助!

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?

解决方案

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!

这篇关于如何将列表分成两个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆