以网格格式打印字符串列表 - Python

Print a list of strings in a grid format - Python

虽然这个问题与这里的其他几个问题相似,但现有的许多答案confusing/difficult让我无法理解。

无论如何,我只是想知道是否有办法打印列表,像这样:["a", "b", "c", "d"] 以网格格式(在 python IDLE 中),

像这样...

a b
c d

如有任何帮助,我们将不胜感激。谢谢

这是一种方法:

l = ["a", "b", "c", "d"]

def printGrid (numsPerRow, l):
    printStr = ""
    numsInRow = 1
    for i in range(len(l)):

        item = l[i]
        if numsInRow % numsPerRow == 0:
            printStr += "{0}\n".format(item)
            numsInRow = 1
        else:
            printStr += "{0}\t".format(item)
            numsInRow += 1
    return printStr

print printGrid(2, l)

或者您可以使用列表而不是字符串操作来做到这一点:

l = ["a", "b", "c", "d"]

def printGrid (numsPerRow, l):
    copyL = l[:]
    numsInRow = 1
    for i in range(len(l)):
        if numsInRow % numsPerRow == 0:
            copyL[i] = copyL[i] + "\n"
            numsInRow = 1
        else:
            copyL[i] = copyL[i] + "\t"
            numsInRow += 1
    return copyL

print "".join(printGrid(2, l)) ,
print l

您可以使用 for 循环,step 等于您的网格宽度和切片,将您的字符连接成字符串,中间有空格。在我的解决方案中,我应用字符串而不是字符列表。字符串 == 字符列表。不要忘记这一点。

>>> strq
'abcdefghijk'

这将是您的代码:

>>> n = 3
>>> for el in range(0,len(strq),n):
...     if el < len(strq)-(n-1):
...         print ' '.join(list(strq[el:el+n]))
...     else:
...         print ' '.join(list(strq[el:]))
... 
a b c
d e f
g h i
j k
>>> n = 4
>>> for el in range(0,len(strq),n):
...     if el < len(strq)-(n-1):
...         print ' '.join(list(strq[el:el+n]))
...     else:
...         print ' '.join(list(strq[el:]))
... 
a b c d
e f g h
i j k
>>>