有没有办法将Python元组扩展为函数 - 作为实际参数?
例如,这里expand()有魔力:
some_tuple = (1, "foo", "bar")
def myfun(number, str1, str2):
return (number * 2, str1 + str2, str2 + str1)
myfun(expand(some_tuple)) # (2, "foobar", "barfoo")
Run Code Online (Sandbox Code Playgroud)
我知道可以定义myfun为myfun((a, b, c)),但当然可能有遗留代码.谢谢
zip如果迭代的长度不相等,我正在寻找一个很好的方法来引发异常的几个迭代.
在迭代项是列表或具有len方法的情况下,此解决方案简洁明了:
def zip_equal(it1, it2):
if len(it1) != len(it2):
raise ValueError("Lengths of iterables are different")
return zip(it1, it2)
Run Code Online (Sandbox Code Playgroud)
但是,如果it1和it2是生成器,则前一个函数将失败,因为未定义长度TypeError: object of type 'generator' has no len().
我想这个itertools模块提供了一种简单的方法来实现它,但到目前为止我还没有找到它.我想出了这个自制的解决方案:
def zip_equal(it1, it2):
exhausted = False
while True:
try:
el1 = next(it1)
if exhausted: # in a previous iteration it2 was exhausted but it1 still has elements
raise ValueError("it1 and it2 have different lengths")
except StopIteration:
exhausted = True
# it2 must …Run Code Online (Sandbox Code Playgroud) 所以我陷入了一个我正在研究的涉及python命令行的项目.
基本上,这就是我想要完成的事情:
我在课堂上有一套功能,比方说,
def do_option1(self, param1, param2) :
#some python code here
def do_option2(self, param1):
#some python code here
def do_option3(self, param1, param2, param3):
#some python code here
Run Code Online (Sandbox Code Playgroud)
基本上,当用户filename.py option2 param1进入命令行时,我希望它调用该函数do_option2并将参数传递param1给它.
类似地,当用户放置时filename.py option3 param1 param2 param3,我希望它使用给定的参数执行do_option3函数.
我知道有2个模块的蟒蛇叫argparse和optparse,但我已经很难理解这两个,我不知道,如果单独两个会完成我需要做.
python command-line optparse command-line-arguments argparse
如何像javascript一样将数组破坏为参数列表?
def foo( arg0, arg1 ): pass
bar = [ 32, 44 ]
foo( ...bar )
Run Code Online (Sandbox Code Playgroud) 我似乎无法找到一种直接的方法来编写代码来查找要格式化的项目数,向用户询问参数,并将它们格式化为原始形式。
我正在尝试做的一个基本示例如下(用户输入在“>>>”之后开始):
>>> test.py
What is the form? >>> "{0} Zero {1} One"
What is the value for parameter 0? >>> "Hello"
What is the value for parameter 1? >>> "Goodbye"
Run Code Online (Sandbox Code Playgroud)
然后程序将使用 print(form.format()) 来显示格式化的输入:
Hello Zero Goodbye One
Run Code Online (Sandbox Code Playgroud)
但是,如果表单有 3 个参数,它将要求参数 0、1 和 2:
>>> test.py (same file)
What is the form? >>> "{0} Zero {1} One {2} Two"
What is the value for parameter 0? >>> "Hello"
What is the value for parameter 1? >>> "Goodbye"
What is the …Run Code Online (Sandbox Code Playgroud) 是否可以使用单个数据结构传递给具有多个参数的函数?我想做类似以下的事情,但它似乎不起作用.
foo_bar = (123, 546)
def a(foo, bar):
print(foo)
print(bar)
Run Code Online (Sandbox Code Playgroud)
是否可以执行以下操作:
a(foo_bar)
Run Code Online (Sandbox Code Playgroud)
代替:
a(foo_bar[0], foo_bar[1])
Run Code Online (Sandbox Code Playgroud)
这样做的pythonic方法是什么?