Python 在列表的不同行上连续打印 5 个项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30451252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:26:46  来源:igfitidea点击:

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

python

提问by Ka-Wa Yip

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

采纳答案by Burger King

It needs to invoke for-loopand joinfunctions 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

回答by moffeltje

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

回答by ZdaR

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

回答by fiacre

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 的方式来完成这项任务。

回答by csharpcoder

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)

你可以像下面这样更简单,将你的列表分成子列表,这看起来更像 Pythonic。然后随心所欲地打印它。也不要使用列表,因为它是关键字(不推荐)

sub_list1=[list1[x:x+5] for x in xrange(0, len(list1), 5)]
for each in sub_list1:
    print( ''.join(each))

回答by dabhand

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

另一种选择,打印后的逗号表示没有换行符

回答by Mark VY

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 %sstrings :) Here's version 0:

这里有很多答案告诉你如何去做,但没有解释如何弄清楚。我喜欢用来找出循环的技巧是手动编写前几次迭代,然后寻找模式。此外,首先忽略边缘情况。在这里,明显的边缘情况是:如果列表的大小不是 5 的倍数怎么办?别担心!在这个答案中,我将尽量避免使用任何能让我们更轻松的花哨语言功能,而是手动完成所有事情,这是一种艰难的方式。这样我们就可以专注于基本思想而不是酷炫的 Python 功能。(Python 有很多很酷的特性。老实说,我不确定我是否能抗拒它们,但我会尝试。)我将使用 print 语句而不是thefile.write,因为我认为它更容易阅读。 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. 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:

最后,我们准备好解决大多数数字不是 5 的倍数这一恼人的事实。在这种情况下,上面的代码基本上会崩溃。让我们尝试修复它而不用想太多。做这件事有很多种方法; 这是我想出的;我们鼓励您在查看我所做的之前尝试提出自己的想法。(或者,如果您愿意,可以在偷看之后。)第 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. And we find that dabhand's answer is almost exactly what we have, except that it uses enumerateso 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:

现在漂亮多了!在这一点上,我们已经努力工作,并通过查看 Python 具有哪些很酷的特性来使这段代码变得更好来奖励自己。我们发现 dabhand 的答案几乎就是我们所拥有的,只是它使用enumeratePython 来跟踪我们正在使用的数字。它只为我们节省了两行代码,但是在如此短的循环中,它几乎将我们的行数减少了一半 :) 第 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 :)

这是我的最终版本。这里很多人建议使用join. 对于这个问题,这是一个好主意,你不妨使用它。问题是如果您遇到不同的问题,这将无济于事。即使 Python 没有预煮的解决方案,DIY 方法也能奏效 :)

回答by Vorsprung

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

回答by J?rn Hees

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 ZdaRis preferable as it is considerably faster.

如果不考虑 RAM,则ZdaR答案更可取,因为它要快得多。

回答by Plo_Koon

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