如何垂直显示列表? [英] How to display a list vertically?

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

问题描述

我有一个字母列表,希望能够像这样垂直显示它们:

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.

那不是那么容易,您需要先想一想,然后意识到如果您计算列表的一半并将其保留: h = len(letters)//2 可以使用变量 i 遍历列表的前半部分,并在同一行中打印 letters [i] letters [h + i] 正确的?像这样:

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? 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.

话虽如此,通过使用Python,您可以走的更远:).看这段代码:

That being said, by using Python you can go further :). 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)

这将在Python 3中输出以下内容:

This will output the following in Python 3:

a d
b e
c f

我刚才做的是带有 zip的表单元组 函数将列表的两半分组.

What I just did was form tuples with zip function grouping the two halves of the list.

出于完整性考虑,如果某天您的列表没有成对长度,则可以使用 itertools.zip_longest 或多或少地类似于 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.

希望这会有所帮助!

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

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