有没有办法在不使用Python中的for循环的情况下在元组中查找项目?

Joa*_*nge 5 python loops tuples

我有一个Control值元组,我想找到一个具有匹配名称的元组.现在我用这个:

listView
for control in controls:
    if control.name == "ListView":
        listView = control
Run Code Online (Sandbox Code Playgroud)

我可以比这简单吗?也许是这样的:

listView = controls.FirstOrDefault(c => c.name == "ListView")
Run Code Online (Sandbox Code Playgroud)

And*_*ark 6

这是一个选项:

listView = next(c for c in controls if c.name == "ListView")
Run Code Online (Sandbox Code Playgroud)

请注意,StopIteration如果不存在匹配项,则会引发一个匹配项,因此您需要将其置于try/except中,并在获得a时将其替换为默认值StopIteration.

或者,您可以将默认值添加到iterable中,以便next调用始终成功.

from itertools import chain
listView = next(chain((c for c in controls if c.name == "ListView"), [default])
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Python 2.5或更低版本,则将呼叫从更改next(iterable)iterable.next().