简体   繁体   English

在单独的行中连续打印5个项目以获取列表?

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

I have a list of unknown number of items, let's say 26. let's say 我有一个未知数量的项目列表,让我们说26.让我们说

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']

How to print like this: 如何打印像这样:

abcde

fghij

klmno

pqrst

uvwxy

z

? Thank you very much. 非常感谢你。 Attempt: 尝试:

    start = 0
    for item in list:
        if start < 5:
            thefile.write("%s" % item)
            start = start + 5
        else:
            thefile.write("%s" % item)
            start = 0

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 . 你可以通过列表理解来简单地做到这一点: "\\n".join(["".join(lst[i:i+5]) for i in xrange(0,len(lst),5)]) xrange(start, end, interval)这里给出一个在5的距离上等距离的整数列表,然后我们通过使用列表切片将给定列表切成长度为5的小块。

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. 然后.join()方法执行名称建议,它通过放置给定字符并返回字符串来连接列表的元素。

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
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 另一种选择,打印后的逗号表示没有换行符

It needs to invoke for-loop and join functions can solve it. 它需要调用for-loopjoin函数才能解决它。

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

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? 在这里,明显的边缘情况是:如果列表的大小不是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功能。 (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. (Python有很多很酷的功能。老实说,我不确定我是否可以抵抗它们,但我会尝试。)我将使用print语句而不是thefile.write ,因为我觉得它更容易阅读。 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语句写入文件: print >> thefile, l[0] ,并且不需要所有那些%s字符串:)这里是版本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): 这是版本1(请注意,我们仍然假设列表的大小是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. 最后,我们已经准备好处理大多数数字不是5的倍数的烦人事实。在这种情况下,上述代码基本上会崩溃。 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: (或者,如果你愿意,可以偷看。)第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: 版本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: 第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. 在这一点上,我们努力工作,并通过查看Python有哪些很酷的功能来使这些代码变得更好来奖励自己。 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. 我们发现dabhand的答案几乎就是我们所拥有的,除了它使用enumerate因此Python可以跟踪我们所处的数字。 It only saves us two lines, but with such a short loop, it almost cuts our line count in half :) Version 5: 它只为我们节省了两行,但是如此短的循环,它几乎将我们的行数减少了一半:)版本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 . 这里有很多人建议使用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 :) 即使Python没有预先制作的解决方案,DIY方法仍然有效:)

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. 但我相信有更多的pythonic方式来完成任务。

You can something easier like below , break your list into sub-list , also this seems more Pythonic . 你可以像下面这样更容易,将你的列表分成子列表,这似乎更像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))
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

Just to prove I am really an unreformed JAPH regular expressions are the way to go! 只是为了证明我真的是一个未经改造的JAPH正则表达式是要走的路!

import re
q="".join(lst)
for x in re.finditer('.{,5}',q)
  print x.group()

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: 如果你正在处理一个可能太大而无法容纳在RAM中的可迭代(如文件),你可以使用这样的东西:

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. 如果不考虑RAM ,ZdaR答案是可取的,因为它要快得多。

Python 3+ simple way Python 3+简单的方法

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM