简体   繁体   English

如何垂直显示列表?

[英]How to display a list vertically?

I have a list of letters and want to be able to display them vertically like so:我有一个字母列表,希望能够像这样垂直显示它们:

a d
b e
c f

def main():
    letters = ["a", "b", "c", "d","e", "f"]
    for i in letters:
       print(i)

this code only display them like this:这段代码只像这样显示它们:

a
b
c
d
e

That's because you're printing them in separate lines.那是因为您在单独的行中打印它们。 Although you haven't given us enough info on how actually you want to print them, I can infer that you want the first half on the first column and the second half on the second colum.尽管您没有给我们足够的信息来说明您实际上想要如何打印它们,但我可以推断出您想要第一列的前半部分和第二列的后半部分。

Well, that is not that easy, you need to think ahead a little and realize that if you calculate the half of the list and keep it: h=len(letters)//2 you can iterate with variable i through the first half of the list and print in the same line letters[i] and letters[h+i] correct?嗯,这不是那么容易,您需要提前考虑一下并意识到如果您计算列表的一半并保留它: h=len(letters)//2您可以通过变量i遍历前半部分列表和打印在同一行letters[i]letters[h+i]正确吗? Something like this:像这样的东西:

def main():
    letters = ["a", "b", "c", "d","e", "f"]
    h = len(letters)//2 # integer division in Python 3
    for i in range(h):
       print(letters[i], letters[h+i])

You can easily generalize it for lists without pair length, but that really depends on what you want to do in that case.您可以轻松地将它概括为没有对长度的列表,但这实际上取决于您在这种情况下想要做什么。

That being said, by using Python you can go further :).话虽如此,通过使用 Python,您可以走得更远:)。 Look at this code:看看这段代码:

def main():
    letters = ["a", "b", "c", "d","e", "f"]
    for s1,s2 in zip(letters[:len(letters)//2], letters[len(letters)//2:]): #len(letters)/2 will work with every paired length list
       print(s1,s2)

This will output the following in Python 3:这将在 Python 3 中输出以下内容:

a d
b e
c f

What I just did was form tuples with zip function grouping the two halves of the list.我刚刚做的是使用zip函数将列表的两半分组的形式元组。

For the sake of completeness, if someday your list hasn't a pair length, you can use itertools.zip_longest which works more or less like zip but fills with a default value if both iterables aren't of the same size.为了完整起见,如果有一天你的列表没有一对长度,你可以使用itertools.zip_longest它或多或少像zip一样工作,但如果两个可迭代的大小不同,则填充默认值。

Hope this helps!希望这可以帮助!

I'll just throw in another solution:我只会提出另一个解决方案:

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

for n,i in enumerate(letters[:3]):
    print(i,letters[n+3])

Also outputs:还输出:

a d
b e
c f

Answer Peter Goldsborough has issue回答 Peter Goldsborough 有问题

what about this letters array这个字母数组怎么样

>>> letters = ["a", "b", "c", "d","e"]
>>> for n,i in enumerate(letters[:3]):
    print(i,letters[n+3])


a d
b e
Traceback (most recent call last):
  File "<pyshell#187>", line 2, in <module>
    print(i,letters[n+3])
IndexError: list index out of range

I added condition for it我为它添加了条件

>>> for n,i in enumerate(letters[:3]):
    if n + 3 < len(letters):
        print(i,letters[n+3])
    else:
        print(i)


a d
b e
c

The same problem with Paulo Bu's answer. Paulo Bu的回答也有同样的问题。

And here is my I think more simple and universal solution这是我认为更简单和通用的解决方案

>>> import math
>>> def main():
    letters = ["a", "b", "c", "d", "e", "f"]
    rows = 3
    columns = int(math.ceil(len(letters) / rows))
    for i in range(min(rows, len(letters))):
        for j in range(columns):
            next_column_i = i + rows * j
            if next_column_i < len(letters):
                print(letters[next_column_i], end = ' ')
        print()


>>> main()
a d 
b e 
c f 
>>> 

I can change rows count set it 2 and easy to get this if I need我可以更改行数将其设置为 2,如果需要,可以轻松获得

>>> main()
a c e 
b d f 
>>> 

If the goal is to specify the number of COLUMNS in which to display a collections, here's my code如果目标是指定显示集合的 COLUMNS 数,这是我的代码

# Python 3

from math import ceil

def pt(x, nbcol):
    print ('nbcol ==',nbcol)
    y = int(ceil(len(x)/float(nbcol)))
    wcol = len(x)//y
    if wcol==nbcol or (wcol+1==nbcol and 0 < len(x) - (wcol*y) <= y):
        print ('\n'.join('\t'.join(str(el) for el in x[i::y])
                         for i in range(y)) , '\n' )
    else:
        print ("I can't do it\n")


li = ['ab','R','uio','b',4578,'h','yu','mlp','AZY12','78']
for nbcol in range(1,9):
    pt(li,nbcol)
print ('===============================')
for nbcol in range(1,9):
    pt("abcdef",nbcol)
print ('===============================')
for nbcol in range(1,9):
    pt('abcdefghijk',nbcol)

example例子

nbcol == 1
ab
R
uio
b
4578
h
yu
mlp
AZY12
78 

nbcol == 2
ab  h
R   yu
uio mlp
b   AZY12
4578    78 

nbcol == 3
ab  4578    AZY12
R   h   78
uio yu
b   mlp 

nbcol == 4
ab  b   yu  78
R   4578    mlp
uio h   AZY12 

nbcol == 5
ab  uio 4578    yu  AZY12
R   b   h   mlp 78 

nbcol == 6
I can't do it

nbcol == 7
I can't do it

nbcol == 8
I can't do it

===============================
nbcol == 1
a
b
c
d
e
f 

nbcol == 2
a   d
b   e
c   f 

nbcol == 3
a   c   e
b   d   f 

nbcol == 4
I can't do it

nbcol == 5
I can't do it

nbcol == 6
a   b   c   d   e   f 

nbcol == 7
I can't do it

nbcol == 8
I can't do it

===============================
nbcol == 1
a
b
c
d
e
f
g
h
i
j
k 

nbcol == 2
a   g
b   h
c   i
d   j
e   k
f 

nbcol == 3
a   e   i
b   f   j
c   g   k
d   h 

nbcol == 4
a   d   g   j
b   e   h   k
c   f   i 

nbcol == 5
I can't do it

nbcol == 6
a   c   e   g   i   k
b   d   f   h   j 

nbcol == 7
I can't do it

nbcol == 8
I can't do it

Without context for what you are doing it is difficult to provide an answer.如果没有你正在做的事情的背景,就很难提供答案。

If your data need to be in pairs then perhaps you should create a differently structured object.如果您的数据需要成对出现,那么您或许应该创建一个不同结构的对象。 A simple example would be a list of tuples.一个简单的例子是元组列表。

def main():
    letters = [("a", "d"), ("b", "e"), ("c", "f")]
    for pair in letters:
       print("%s %s" % pair)

For a general solution, you can do something along these lines:对于通用解决方案,您可以按照以下方式进行操作:

from itertools import zip_longest

lets = list('abcdefghijklmnop')

def table(it, rows):
    return zip_longest(*[it[i:i+rows] for i in range(0, len(it), rows)], 
                            fillvalue=' ')

for t in table(lets, 6):
    print(*t) 

Prints:印刷:

a g m
b h n
c i o
d j p
e k 
f l 

Since we are using zip_longest ( izip_longest for Python 2), you can supply a fillvalue and the odd ending value will not be truncated.由于我们使用的是zip_longest (Python 2 的izip_longest ),您可以提供一个填充值并且奇数结束值不会被截断。

If you want to change the columns, change the number of rows:如果要更改列,请更改行数:

for t in table(lets, 2):
    print(*t)  

Prints:印刷:

a c e g i k m o
b d f h j l n p

Of course, it is easy math to figure out the relationship between cols and rows if you have a list X items long.当然,如果您有一个长 X 项的列表,那么计算 cols 和 rows 之间的关系很容易。

So How does this work?那么这是如何工作的呢?

By definition, a table is a matrix.根据定义,表是一个矩阵。 So first, create a matrix that is rows long:因此,首先创建一个矩阵就是rows长:

>>> lets
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
>>> rows=6
>>> [lets[i:i+rows] for i in range(0, len(lets), rows)]
[['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p']]

Then invert that matrix:然后反转该矩阵:

>>> for t in zip_longest(*[lets[i:i+rows] for i in range(0, len(lets), rows)]):
...     print(t)
... 
('a', 'g', 'm')
('b', 'h', 'n')
('c', 'i', 'o')
('d', 'j', 'p')
('e', 'k', None)
('f', 'l', None)

And go from there...然后从那里走...

一个简单的方法是: D=["A","B","C"] print('\\n'.join(D))

>>> letters = ["a", "b", "c", "d", "e", "f", "g"]
>>> odd_even = zip(letters[::2], letters[1::2] + len(letters) % 2 * [""])
>>> pairs = [" ".join([odd, even]) for odd, even in odd_even]
a b
c d
e f
g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM