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
9 个解决方案
#1
7
It needs to invoke for-loop
and join
functions can solve it.
它需要调用for-loop函数,而join函数可以解决这个问题。
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
#2
14
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[我+ 5])我在xrange(0,len(lst),5)])这里的xrange(开始、结束时间间隔)将一列整数等距的距离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
#3
12
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
另一种选择是,打印后的逗号表示没有换行字符
#4
6
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:
这里有很多的答案告诉你怎么做,但是没有一个能解释怎么做。我喜欢用来计算循环的技巧是手工编写前几个迭代,然后寻找一个模式。同样,首先忽略边缘情况。在这里,最明显的边界情况是:如果列表的大小不是5的倍数怎么办?别担心!我将尽量避免使用任何花哨的语言特性,这些特性将使我们在这个答案中更容易地完成工作,而是使用手动的、困难的方法来完成所有工作。通过这种方式,我们可以专注于基本思想,而不是出色的Python特性。(Python有很多很酷的特性。老实说,我不确定我能不能抗拒它们,但我会试一试。我将使用print语句而不是thefile。写作,因为我认为它更容易阅读。您甚至可以使用print语句对文件进行写入:打印>> thefile, l[0],不需要所有这些%s字符串:)
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:
它不再重复,但也不再变短。这可能是查看我们的代码,看看它是否反映了最好的解决方案,或者仅仅反映了我们到达这里的路径的好时机。也许有更简单的方法。实际上,我们为什么要用5块来处理?我们一次吃一个怎么样,但是每5个项目都要特别对待。让我们重新开始。版本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:
这是多漂亮!在这一点上,我们已经努力工作了,并且通过观察Python有哪些很酷的特性使代码更漂亮来奖励自己。我们发现dabhand的答案几乎和我们的一样,除了它使用了enumerate Python来跟踪我们所在的数字。它只节省了两行代码,但是如此短的循环,几乎把我们的行数减少了一半。
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方法也可以工作:)
#5
4
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)
你可以做一些更简单的事情,比如下面,把你的列表分成子列表,这看起来更符合python语言。然后你想怎么打印就怎么打印。也不要使用list,因为它是关键字(不推荐)
sub_list1=[list1[x:x+5] for x in xrange(0, len(list1), 5)]
for each in sub_list1:
print( ''.join(each))
#6
4
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.
但是我相信有一种更大的方法来完成这个任务。
#7
3
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
#8
1
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()
#9
1
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给出的答案更可取,因为它要快得多。
#1
7
It needs to invoke for-loop
and join
functions can solve it.
它需要调用for-loop函数,而join函数可以解决这个问题。
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
#2
14
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[我+ 5])我在xrange(0,len(lst),5)])这里的xrange(开始、结束时间间隔)将一列整数等距的距离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
#3
12
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
另一种选择是,打印后的逗号表示没有换行字符
#4
6
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:
这里有很多的答案告诉你怎么做,但是没有一个能解释怎么做。我喜欢用来计算循环的技巧是手工编写前几个迭代,然后寻找一个模式。同样,首先忽略边缘情况。在这里,最明显的边界情况是:如果列表的大小不是5的倍数怎么办?别担心!我将尽量避免使用任何花哨的语言特性,这些特性将使我们在这个答案中更容易地完成工作,而是使用手动的、困难的方法来完成所有工作。通过这种方式,我们可以专注于基本思想,而不是出色的Python特性。(Python有很多很酷的特性。老实说,我不确定我能不能抗拒它们,但我会试一试。我将使用print语句而不是thefile。写作,因为我认为它更容易阅读。您甚至可以使用print语句对文件进行写入:打印>> thefile, l[0],不需要所有这些%s字符串:)
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:
它不再重复,但也不再变短。这可能是查看我们的代码,看看它是否反映了最好的解决方案,或者仅仅反映了我们到达这里的路径的好时机。也许有更简单的方法。实际上,我们为什么要用5块来处理?我们一次吃一个怎么样,但是每5个项目都要特别对待。让我们重新开始。版本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:
这是多漂亮!在这一点上,我们已经努力工作了,并且通过观察Python有哪些很酷的特性使代码更漂亮来奖励自己。我们发现dabhand的答案几乎和我们的一样,除了它使用了enumerate Python来跟踪我们所在的数字。它只节省了两行代码,但是如此短的循环,几乎把我们的行数减少了一半。
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方法也可以工作:)
#5
4
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)
你可以做一些更简单的事情,比如下面,把你的列表分成子列表,这看起来更符合python语言。然后你想怎么打印就怎么打印。也不要使用list,因为它是关键字(不推荐)
sub_list1=[list1[x:x+5] for x in xrange(0, len(list1), 5)]
for each in sub_list1:
print( ''.join(each))
#6
4
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.
但是我相信有一种更大的方法来完成这个任务。
#7
3
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
#8
1
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()
#9
1
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给出的答案更可取,因为它要快得多。