簡體   English   中英

如何遍歷字符串列表並以 Tabula 形式打印

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

正在練習 python 我在這里遇到這個問題,我有一個包含三個團隊的列表, teams = ['manu','spurs','roma']只是遍歷索引 0 我能夠打印結果

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

` 但我能以表格形式打印所有團隊嗎看圖片

幫忙

您可以嘗試這樣做。 使用 try/except 塊在 for 循環中逐個字母打印。 在打印索引“x”中的所有字母后,使用print(end='\n')創建新行。 (您可以編寫不帶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')

你的數據固定了嗎? 因為如果不是,也許您已經知道如何獲取您擁有的數據並將其放入循環中。 無論如何,這可能對您有所幫助。

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

--更新---

我總覺得我以前見過這個……幸運的是我找到了它,如果你願意,你可以這樣擁有它。 多虧了這個

from itertools import zip_longest

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

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

K.Oleksy 的響應很好,但使用異常來捕獲字符串的末尾。 我會告訴你如何避免這種情況,因為沒有例外。

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