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

前端 未结 11 924
耶瑟儿~
耶瑟儿~ 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:36

    You can something easier like below , break your list into sub-list , also this seems more Pythonic . Then print it how ever u want . Also don't use list as it's a keyword(not recommended)

    sub_list1=[list1[x:x+5] for x in xrange(0, len(list1), 5)]
    for each in sub_list1:
        print( ''.join(each))
    
    0 讨论(0)
  • 2021-02-07 19:37

    Lots of answers here saying you how to do it, but none explaining how to figure it out. The trick I like to use to figure out a loop is to write the first few iterations by hand, and then look for a pattern. Also, ignore edge cases at first. Here, the obvious edge case is: what if the size of the list is not a multiple of 5? Don't worry about it! I'm going to try to avoid using any fancy language features that would make things easier for us in this answer, and instead do everything manually, the hard way. That way we can focus on the basic idea instead of cool Python features. (Python has lots of cool features. I'm honestly not sure if I can resist them, but I'll try.) I'm going to use print statements instead of thefile.write, because I think it's easier to read. You can even use print statements to write to files: print >> thefile, l[0], and no need for all those %s strings :) Here's version 0:

    print l[0], l[1], l[2], l[3], l[4]
    print l[5], l[6], l[7], l[8], l[9]
    

    This loop is simple enough that two iterations is probably enough, but sometimes you may need more. Here's version 1 (note that we still assume the size of the list is a multiple of 5):

    idx=0
    while idx < len(l):
      print l[idx], l[idx+1], l[idx+2], l[idx+3], l[idx+4]
      a += 5
    

    Finally, we're ready to take care of the annoying fact that most numbers are not a multiple of 5. The above code will basically crash in that case. Let's try to fix it without thinking too hard. There are several ways to do this; this is the one I came up with; you're encouraged to try to come up with your own before peeking at what I did. (Or after peeking if you prefer.) Version 2:

    idx=0
    while idx < len(l):
      print l[index],
      if idx+1 < len(l): print l[idx+1],
      if idx+2 < len(l): print l[idx+2],
      if idx+3 < len(l): print l[idx+3],
      if idx+4 < len(l): print l[idx+4]
      idx += 5
    

    We finally have code that does what we want, but it's not pretty. It's so repetitive that I resorted to copy/paste to write it, and it's not very symmetric either. But we know what to do about repetitive code: use a loop! Version 3:

    idx=0
    while idx < len(l):
      b = 0
      while b < 5:
        if idx+b < len(l): print l[idx+b],
        b += 1
      print
      idx += 5
    

    It's no longer repetitive, but it didn't get any shorter. This might be a good time to look at our code and see if it reflects the best solution, or merely reflects the path we took to get here. Maybe there is a simpler way. Indeed, why are we processing things in blocks of five? How about we go one at a time, but treat every fifth item specially. Let's start over. Version 4:

    idx=0
    while idx < len(l):
      print l[idx],
      if idx % 5 == 4: print
      idx += 1
    

    Now that's much prettier! At this point, we've worked hard, and reward ourselves by looking at what cool features Python has to make this code even nicer. And we find that dabhand's answer is almost exactly what we have, except that it uses enumerate so Python does the work of keeping track of what number we're on. It only saves us two lines, but with such a short loop, it almost cuts our line count in half :) Version 5:

    for idx, item in enumerate(l):
      print item,
      if idx % 5 == 4: print
    

    And that's my final version. Many people here suggest using join. It's a good idea for this problem, and you might as well use it. The trouble is it would not help if you had a different problem. The DIY approach works even when Python does not have a pre-cooked solution :)

    0 讨论(0)
  • 2021-02-07 19:42
    for i, a in enumerate(A):
        print a, 
        if i % 5 == 4: 
            print "\n"
    

    Another alternative, the comma after the print means there is no newline character

    0 讨论(0)
  • 2021-02-07 19:43

    If you're working on an iterable (like a file) which is potentially too big to fit in RAM you can use something like this:

    from itertools import izip_longest
    def chunker(iterable, n, fillvalue=None):
        """Like an itertools.grouper but None values are excluded.
    
        >>> list(chunker([1, 2, 3, 4, 5], 3))
        [[1, 2, 3], [4, 5]]
        """
        if n < 1:
            raise ValueError("can't chunk by n=%d" % n)
        args = [iter(iterable)] * n
        return (
            [e for e in t if e is not None]
            for t in izip_longest(*args, fillvalue=fillvalue)
        )
    
    with open('some_file') as f:
        for row in chunker(f, 5):
            print "".join(row)
    

    If RAM is not a consideration the answer by ZdaR is preferable as it is considerably faster.

    0 讨论(0)
  • 2021-02-07 19:52

    Python 3+ simple way

    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']
    
    for ind, smb in enumerate(lst):
        print(smb, end='')
        if ind%5 == 4: 
            print('\n')
    
    0 讨论(0)
提交回复
热议问题