猿问

如何使用设置为“无”的可选参数

使用命名参数,如何告诉接收器方法使用参数的“未提供”版本?无发送功能不起作用。以下是我的特定代码,请特别注意以下部分:


args=launch[1:] if launch[4] is not None else None

我想尽可能保持列表理解


procs = [Process(name=key, target=launch[0],

               args=launch[1:] if launch[4] is not None else None)

       for key, launch in zip(procinfos.keys(), launches)]

结果是选择了进程的单参数版本,然后抱怨参数为无:


File "<stdin>", line 15, in parallel

          for key, launch in zip(procinfos.keys(), launches)]

File "/usr/lib/python2.7/multiprocessing/process.py", line 104, in __init__

 self._args = tuple(args)

TypeError:“ NoneType”对象不可迭代


当然,有一种蛮力方法:即复制理解的一部分,而只是避免指定args =参数。我可能最终会走那条路线..除非在这里神奇地出现了替代方法;)


米琪卡哇伊
浏览 210回答 3
3回答

侃侃尔雅

您可以使用参数解包将指定的参数指定为字典,args如果则不存在launch[4] is None,例如:procs = []for key, launch in zip(procinfos.keys(), launches):&nbsp; &nbsp; &nbsp;params = {"name": key, "target": launch[0]}&nbsp; &nbsp; &nbsp;if launch[4] is not None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;params["args"] = launch[1:]&nbsp; &nbsp; &nbsp;procs.append(Process(**params))

慕桂英546537

的默认值args是一个空的元组,不是None:launch[1:] if launch[4] is not None else ()我真的会避免编写三行单行代码。常规for循环没有错:processes = []for key, launch in zip(procinfos, launches):&nbsp; &nbsp; args = launch[1:] if launch[4] is not None else ()&nbsp; &nbsp; process = Process(name=key, target=launch[0], args=args)&nbsp; &nbsp; processes.append(process)

临摹微笑

替换None为空的元组:()procs = [Process(name=key, target=launch[0],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;args=launch[1:] if launch[4] is not None else ())&nbsp; &nbsp;for key, launch in zip(procinfos.keys(), launches)]
随时随地看视频慕课网APP

相关分类

Python
我要回答