简体   繁体   English

如何遍历字符串列表并以 Tabula 形式打印

[英]how to loop through a list of strings and print in Tabula form

am practicing python I have this issue here, I have a list of three teams, teams = ['manu','spurs','roma'] just looping through the index 0 i was able to print the outcome正在练习 python 我在这里遇到这个问题,我有一个包含三个团队的列表, teams = ['manu','spurs','roma']只是遍历索引 0 我能够打印结果

 teams = ['manu','spurs','roma'] for m in teams[0]: print(m,'\t')

` but can I print all the teams in a tabula form like ` 但我能以表格形式打印所有团队吗看图片

help out帮忙

You can try to do it something like this.您可以尝试这样做。 Print letter by letter in for loops with try/except block.使用 try/except 块在 for 循环中逐个字母打印。 Use print(end='\n') to create new line after printed all letters from index 'x'.在打印索引“x”中的所有字母后,使用print(end='\n')创建新行。 (You can write print() without end='\n' but it will be less understandable. (您可以编写不带end='\n' print() ,但这样会不太容易理解。

teams = ['manu','spurs','roma']
for x in range(len(max(teams, key=len))):
    for m in teams:
        try:
            print(m[x], end='\t')
        except IndexError:
            print("", end='\t')
    print(end='\n')

Is your data fixed?你的数据固定了吗? Cause if not maybe you already know on how to get those data you have and put it in the loop.因为如果不是,也许您已经知道如何获取您拥有的数据并将其放入循环中。 Anyways this might help you.无论如何,这可能对您有所帮助。

teams = ['manu','spurs','roma']
for m,s,r in zip(teams[0],teams[1],teams[2]):
    print(m,s,r,'\t')

-- UPDATE --- --更新---

I always felt I've seen this before... so luckily I've found it and you can have it this way if you want.我总觉得我以前见过这个……幸运的是我找到了它,如果你愿意,你可以这样拥有它。 Thanks to this多亏了这个

from itertools import zip_longest

teams = ['manu','spurs','roma']
text=' '.join(teams)

for x in zip_longest(*text.split(), fillvalue=' '):
    print ('\t'.join(x))

The repsponse of K.Oleksy is great but uses the exceptions to catch the end of the string. K.Oleksy 的响应很好,但使用异常来捕获字符串的末尾。 I'll juste show you how to avoid that as Exceptions are not made for that.我会告诉你如何避免这种情况,因为没有例外。

teams = ['nusqdgqsdgsq','spjurs','romaaa']

max_lenght = len(max(teams, key = len))
print(max_lenght)
for i in range(max_lenght):
    for team_index in range(len(teams)):
        if (i < len(teams[team_index])):
            print(teams[team_index][i], end = '\t')
        else:
            print('  ', end = '')
    print()

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

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