python的print语句和rang

2024-03-29 08:07:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白以下两种情况:

from __future__ import print_function
if __name__ == '__main__':
    n = int(raw_input())
    print(*range(1,n+1), sep='')

如果n是3

output:123

在第二种情况下

print(range(1,n+1), sep='')

output:[1, 2, 3]

不懂“*”的功能,是跟range还是print语句有关?你知道吗


Tags: namefromimportinputoutputrawifmain
3条回答

它是Python中的Argument Unpacking特性。你知道吗

下面是一个简单的例子:

def f(a,b,c):
    print(a,b,c)

f(1,2,3)
f(*[1,2,3])

所以print(*(1,2,3))等价于print(1,2,3)

请参阅python的Expressions reference

列表的值正在由*运算符解包。以下是文档中的引用:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

Range返回一个元组,该元组由函数调用中的*展开。它相当于print(1,2,3,sep='')。*用于解包未命名的参数。因为它们总是被传递给第一个关键字arg,所以只要任何arg没有得到2个值,就仍然允许使用它们。你知道吗

相关问题 更多 >