Python 在同一行打印数字范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18424899/
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 10:42:58  来源:igfitidea点击:

Print range of numbers on same line

pythonpython-2.7

提问by kyle k

Using python I want to print a range of numbers on the same line. how can I do this using python, I can do it using C by not adding \n, but how can I do it using python.

使用 python 我想在同一行上打印一系列数字。我如何使用 python 来做到这一点,我可以通过不添加来使用 C 来做到这一点\n,但是我如何使用 python 来做到这一点。

for x in xrange(1,10):
    print x

I am trying to get this result.

我试图得到这个结果。

1 2 3 4 5 6 7 8 9 10

采纳答案by blakev

Python 2

蟒蛇 2

for x in xrange(1,11):
    print x,

Python 3

蟒蛇 3

for x in range(1,11):
    print(x, end=" ") 

回答by subhash kumar singh

Same can be achieved by using stdout.

使用stdout.

>>> from sys import stdout
>>> for i in range(1,11):
...     stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10 

Alternatively, same can be done by using reduce():

或者,可以使用reduce()以下方法完成相同的操作:

>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>

回答by ersran9

str.joinwould be appropriate in this case

str.join在这种情况下是合适的

>>> print ' '.join(str(x) for x in xrange(1,11))
1 2 3 4 5 6 7 8 9 10 

回答by bre

for i in range(1,11):
    print(i)

i know this is an old question but i think this works now

我知道这是一个老问题,但我认为这现在有效

回答by Anubhav

for i in range(10):
    print(i, end = ' ')

You can provide any delimiter to the end field (space, comma etc.)

您可以为结束字段提供任何分隔符(空格、逗号等)

This is for Python 3

这适用于 Python 3

回答by voidpro

>>>print(*range(1,11)) 
1 2 3 4 5 6 7 8 9 10

Python one liner to print the range

Python 一个班轮来打印范围

回答by Akash Kumar Seth

[print(i, end = ' ') for i in range(10)]
0 1 2 3 4 5 6 7 8 9

This is a list comprehension method of answer same as @Anubhav

这是与@Anubhav 相同的答案列表理解方法

回答by Rajnish Gaur

This is an old question, xrangeis not supported in Python3.

这是一个老问题,xrangePython3 不支持。

You can try -

你可以试试 -

print(*range(1,11)) 

OR

或者

for i in range(10):
    print(i, end = ' ')

回答by Prashant Mani

Though the answer has been given for the question. I would like to add, if in case we need to print numbers without any spaces then we can use the following code for i in range(1,n): print(i,end="")

虽然已经给出了问题的答案。我想补充一下,如果我们需要打印没有任何空格的数字,那么我们可以对 i in range(1,n) 使用以下代码:print(i,end="")

回答by Mykel

Another single-line Python 3 option but with explicit separator:

另一个单行 Python 3 选项,但带有显式分隔符:

print(*range(1,11), sep=' ')

print(*range(1,11), sep=' ')