Print 5 items in a row on separate lines for a list?

前端 未结 11 941
耶瑟儿~
耶瑟儿~ 2021-02-07 19:15

I have a list of unknown number of items, let\'s say 26. let\'s say

list=[\'a\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',
\'i\',\'j\',\'k\',\'l\',\'m\',\'n\',\'         


        
相关标签:
11条回答
  • 2021-02-07 19:25

    You can simple do this by list comprehension: "\n".join(["".join(lst[i:i+5]) for i in xrange(0,len(lst),5)]) the xrange(start, end, interval) here would give a list of integers which are equally spaced at a distance of 5, then we slice the given list in to small chunks each with length of 5 by using list slicing.

    Then the .join() method does what the name suggests, it joins the elements of the list by placing the given character and returns a string.

    lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    
    print "\n".join(["".join(lst[i:i+5]) for i in xrange(0,len(lst),5)])
    
    >>> abcde
        fghij
        klmno
        pqrst
        uvwxy
        z
    
    0 讨论(0)
  • 2021-02-07 19:27

    I think the most cleaner way to write this would be

    list=['a','b','c','d','e','f','g','h', 'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    
    for i in range(0, len(list), 5):
        print(*list[i:i+5], sep='')
    
    0 讨论(0)
  • 2021-02-07 19:31

    It needs to invoke for-loop and join functions can solve it.

    l=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    
    for i in range(len(l)/5+1):
        print "".join(l[i*5:(i+1)*5]) + "\n"
    

    Demo:

    abcde
    
    fghij
    
    klmno
    
    pqrst
    
    uvwxy
    
    z
    
    0 讨论(0)
  • 2021-02-07 19:32
    start = 0
    for item in list:
        if start < 4:
            thefile.write("%s" % item)
            start = start + 1
        else:                             #once the program wrote 4 items, write the 5th item and two linebreaks
            thefile.write("%s\n\n" % item)
            start = 0
    
    0 讨论(0)
  • 2021-02-07 19:33

    Just to prove I am really an unreformed JAPH regular expressions are the way to go!

    import re
    q="".join(lst)
    for x in re.finditer('.{,5}',q)
      print x.group()
    
    0 讨论(0)
  • 2021-02-07 19:34

    This will work:

    n = m = 0
    while m < len(l):
        m = m+5
        print("".join(l[n:m]))
        n = m
    

    But I believe there is a more pythonic way to accomplish the task.

    0 讨论(0)
提交回复
热议问题