2010-07-09 6 views
0

Dire que j'ai une listePython: Imprimer en rangées

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

Comment pourrais-je imprimer la liste dans les lignes contenant 4 colonnes, il ressemblerait à ceci:

apple pear tomato bean 
carrot grape 

Répondre

3
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]) 
0

Essayez avec cette

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 
0
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 
Questions connexes