开发者

Python: Print in rows

开发者 https://www.devze.com 2023-01-06 03:32 出处:网络
Say I have a list food_list = [\'apple\', \'pear\', \'tomato\', \'bean\', \'carrot\', \'grape\'] How would I print the list in rows contain开发者_如何学编程ing 4 columns, so it would look like:

Say I have a list

food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']

How would I print the list in rows contain开发者_如何学编程ing 4 columns, so it would look like:

apple pear tomato bean   
carrot grape


food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
for i in xrange(0, len(food_list), 4):
    print '\t'.join(food_list[i:i+4])


Try with this

food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
size = 4
g = (food_list[i:i+size] for i in xrange(0, len(food_list), size))
for i in g:
    print i


food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
index = 0
for each_food in food_list:
    if index < 3:
            print each_food,
            index += 1
    else:
            print each_food
            index = 0
0

精彩评论

暂无评论...
验证码 换一张
取 消