Anu*_*rma 3 python parameters function list
是否可以以列表的形式输入函数的参数.例如 -
list1 = ["somethin","some"]
def paths(list):
import os
path = os.path.join() #I want to enter the parameters of this function from the list1
return path
Run Code Online (Sandbox Code Playgroud)
好的,我得到了我的答案,但只是一个附加问题,仅与此相关 - 这是我的代码 -
def files_check(file_name,sub_directories):
"""
file_name :The file to check
sub_directories :If the file is under any other sub directory other than the application , this is a list.
"""
appname = session.appname
if sub_directories:
path = os.path.join("applications",
appname,
*sub_directories,
file_name)
return os.path.isfile(path)
else:
path = os.path.join("applications",
appname,
file_name)
return os.path.isfile(path)
Run Code Online (Sandbox Code Playgroud)
我收到此错误 -
SyntaxError: only named arguments may follow *expression
Run Code Online (Sandbox Code Playgroud)
请帮我 .
您可以使用splat运算符()解压缩序列*:
path = os.path.join(*my_list)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> import os
>>> lis = ['foo', 'bar']
>>> os.path.join(*lis)
'foo\\bar'
Run Code Online (Sandbox Code Playgroud)
更新:
要回答你的新问题,一旦你*在参数中使用了你就不能传递位置参数,你可以在这里做类似的事情:
from itertools import chain
def func(*args):
print args
func(1, 2, *chain(range(5), [2]))
#(1, 2, 0, 1, 2, 3, 4, 2)
Run Code Online (Sandbox Code Playgroud)
并且不要list用作变量名
| 归档时间: |
|
| 查看次数: |
568 次 |
| 最近记录: |