[英]Passing a list as several arguments
I'm trying to use a list as arguments, using the : 我正在尝试使用列表作为参数,使用:
>>> l = [1,2,3]
>>> print( *l )
I got an error : 我有一个错误:
File "<stdin>", line 1
t*
^
SyntaxError: invalid syntax
I'm using python 2.7 : 我正在使用python 2.7:
>>> import sys
>>> print sys.version
2.7.3 (default, Jan 2 2013, 13:56:14)
[GCC 4.7.2]
What am I missing ? 我想念什么? Thank you !
谢谢 ! :)
:)
By default, print
isn't a function in Python 2.7. 默认情况下,
print
在Python 2.7中不是功能。 To use the function instead of the statement in a given module, use a future statement: 要使用函数而不是给定模块中的语句,请使用future语句:
from __future__ import print_function
This needs to go at the top of your file, before any code that isn't a future statement (or the module docstring), because the compiler needs to see future statements first to compile the rest of the module differently based on the future statement. 这需要放在文件的顶部,而不是不是future语句(或模块docstring)的任何代码之前,因为编译器需要先查看future语句,然后才能根据future语句以不同的方式编译模块的其余部分。
print
is NOT a function in Python 2.7. 在Python 2.7中
print
不是函数。 It is a statement. 这是一个声明。 So, you should do
所以,你应该做
print l # [1, 2, 3]
If you want to use print
as a function in Python 2.7, you should import print_function
from __future__
, like this 如果你想使用
print
在Python 2.7的功能,你应该导入print_function
从__future__
,像这样
from __future__ import print_function
l = [1,2,3]
print(l) # [1, 2, 3]
print(*l) # 1 2 3
如果要使用print
作为函数,则必须使用__future__
或将python升级到3+
Is this what you are searching for? 这是您要搜索的吗?
>>> l = [1, 2, 3]
>>> def x(*args):
... print args[0]
... print args
>>> x(*l)
1
(1, 2, 3)
If yes, take also a look at Arbitrary Argument Lists in the Python documenation. 如果是,请同时查看Python文档中的“ 任意参数列表 ”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.