python一行由10个元素组成

时间:2016-03-30 23:38:19

标签: python python-2.7 line-breaks

所以我必须写入标准输出100的数字,但是在一行中只放了10个数字,我写的代码几乎是完美但输出如下:

23456789101
5378566145 
8353464573 
7596745634 
4352362356 
2342345346 
2553463221 
9873422358 
8223552233 
578942378

并且有代码:

import sys
import random as r

UPTO = 100

def main():
    for i in xrange(UPTO):
        if i % 10 == 0 and i != 0:
            sys.stdout.write(str(r.randint(0, 9)) + '\n')
        else:
            sys.stdout.write(str(r.randint(0, 9))) 
    print

我怎么能完美地做到这一点?

6 个答案:

答案 0 :(得分:1)

更改你的循环:

for i in xrange(1, UPTO + 1):

代码:

import sys
import random as r

UPTO = 100

def main():
    for i in xrange(1, UPTO + 1):
        if i % 10 == 0 and i != 0:
            sys.stdout.write(str(r.randint(0, 9)) + '\n')
        else:
            sys.stdout.write(str(r.randint(0, 9))) 
    print
main()

输出:

5324707535
0662651201
6774603548
2062356640
2371234722
0295841132
5498111577
0871557117
3062255375
2219008944

答案 1 :(得分:1)

您需要从1开始并转到UPTO + 1

for i in xrange(1, UPTO + 1):

一旦你改变了你的代码:

In [18]: main()
3989867912
0729456107
3457245171
4564003409
3400380373
1638374598
5290288898
6348789359
4628854868
4172212396

您还可以将print作为一项功能,使用__future__导入来简化代码:

from __future__ import print_function

import random as r

UPTO = 100

def main():
    # use a step of 10
    for i in range(0, UPTO, 10):
        # sep="" will leave no spaces between, end="" removes newline
        print(*(r.randint(0, 9) for _ in range(10)), end="", sep="")
        print()

答案 2 :(得分:1)

我会从python3导入print并使用:

from __future__ import print_function
import random

UPTO = 100
for i in xrange(100):
    for j in xrange(10):
        print(random.randint(0,9), end='')
    print()

答案 3 :(得分:0)

正如其他人所指出的那样,修复现有代码只是从1开始,而不是0(或者在测试剩余部分时将{1}加到i。)

但你根本不需要重新发明轮子。您可以使用textwrap.wrap简化自动换行。只需一次生成输出数据,例如:

digits = 100
# Make a 100 long string of digits
alltext = ''.join(str(random.randrange(10)) for _ in range(digits))

# Or to achieve the same effect more efficiently:
alltext = str(random.randrange(10**(digits-1), 10**digits))

然后使用textwrap.wrap并循环到print它:

import textwrap

for line in textwrap.wrap(alltext, width=10):
    print line

获得(例如):

4961561591
3969872520
1896401684
8608153539
0210068022
3975577783
8321168859
8214023841
8138934528
7739266079

答案 4 :(得分:0)

听起来好好使用itertools grouper食谱。

import itertools

def grouper(iterable, n, fillvalue=""):
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args, fillvalue=fillvalue)

UPTO = 100

digits = [str(random.randint(0, 9)) for _ in range(UPTO)]

sys.stdout.write("\n".join(map("".join, grouper(digits, 10)))

答案 5 :(得分:0)

对于python2

from random import randint
import sys
for i in range(100):
  sys.stdout.write(str(randint(0,9))+("\n" if i%10==9 else ""))

或者如果您允许"打印"函数而不是print语句

from __future__ import print_function
from random import randint
for i in range(100):
  print(randint(0,9), end="\n" if i%10==9 else "")