【问题标题】:How do I split up a list into two colums?如何将列表分成两列?
【发布时间】:2017-10-04 18:05:11
【问题描述】:

比如说我有这个列表:

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

我需要做什么才能像这样将它打印到外壳上:

a    d
b    e
c    f

有什么想法吗?

【问题讨论】:

  • @Mitch 不,这是一个错误,我还没有完成编辑。
  • 为什么不分成 2 个列表然后打印出来?
  • 对我来说似乎是一个合法的问题,不知道为什么它被否决了。 +1

标签: python list multiple-columns


【解决方案1】:

这是一个有趣的解决方案,它很容易理解,并且无论列表元素的数量(奇数或偶数)如何都可以工作。

基本上,这会将列表除以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

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    快速回答:

    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
    

    【讨论】:

      猜你喜欢
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2023-02-03
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多