如何在Python中按顺序打印列表中的字符串?

时间:2016-01-23 19:48:41

标签: list python-3.x printing sequence

假设一个列表:s = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]

我了解如何打印列表中的每个项目:

for i in s:
    print (i)

给出:

A
B
C
D
E
F
G
H
I
J

但是假设我想按n分割打印。如果是n = 3

A
B
C

D
E
F

G
H
I

J

这些是我的尝试:

k = 0
for i in s:
    while k < n:
        k += 1
        print (i)

k = 0
while k < n:
    for i in s:
        print (i)
    k += 1

我明白我的尝试已经过时了,但我似乎无法得到它。 我知道你可以用n创建子列表并以这种方式解决它,但有没有办法可以做到这一点呢?

2 个答案:

答案 0 :(得分:1)

k = 0
for i in s:
    if k == n-1:
       print i + '\n'
       k = 0
    else:
        print i
        k += 1

答案 1 :(得分:0)

>>> s = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
>>> n=3
>>> print('\n\n'.join(['\n'.join(s[i:i+n]) for i in range(0,len(s),n)]))
A
B
C

D
E
F

G
H
I

J