This question already has answers here:
How do you split a list into evenly sized chunks?
                                
                                    (62个答案)
                                
                        
                                6年前关闭。
            
                    
所以我有一个清单:

names = ['dog','cat','mouse','moose','rabbit','horse','apple','banana','orange']


我希望输出是这样的:

dog cat mouse moose rabbit horse
apple banana orange


因此,基本上每行显示六个字。

老实说,我不知道从哪里开始,因为这样的for循环每行将显示1:

for i in names:
   print(i)

output -->
dog
cat
mouse
moose
rabbit
horse
apple
banana
orange

最佳答案

您可以使用range进行拆分:

names = ['dog','cat','mouse','moose','rabbit','horse','apple','banana','orange']

for i in range(0, len(names), 6):
    print(names[i:i + 6])

关于python - 如何每行显示一定数量的单词? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15917690/

10-12 23:48