有没有一种方法可以在Python中不使用for循环来查找元组中的项目?
我有一组 Control
值,我想找到具有匹配名称的值。现在我用这个:
listView
for control in controls:
if control.name == "ListView":
listView = control
我可以做得比这更简单吗?也许是这样的:
listView = controls.FirstOrDefault(c => c.name == "ListView")
I have a tuple of Control
values and I want to find the one with a matching name. Right now I use this:
listView
for control in controls:
if control.name == "ListView":
listView = control
Can I do it simpler than this? Perhaps something like:
listView = controls.FirstOrDefault(c => c.name == "ListView")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里有一个选项:
请注意,如果不存在匹配项,这将引发
StopIteration
,因此您需要将其放入 try/ except 中,并在获得时将其替换为默认值停止迭代。
或者,您可以将默认值添加到可迭代对象中,以便
next
调用始终成功。如果您使用的是 Python 2.5 或更低版本,请将调用从
next(iterable)
更改为iterable.next()
。Here is one option:
Note that this will raise a
StopIteration
if no matching item exists, so you will need to put this in a try/except and replace it with a default if you get aStopIteration
.Alternatively you can add your default value to the iterable so the
next
call always succeeds.If you are using Python 2.5 or lower change the call from
next(iterable)
toiterable.next()
.出于纯粹的好奇,我将自己的答案与您的原始代码和FJ的解决方案结合起来,进行性能对比测试。
看来您的解决方案是所有解决方案中最快的。我的解决方案检查控件元组的所有可能元素,因此随着元组大小的增加,它会变慢。
这是代码:
这是我系统上的输出:
HTH! :)
Out of sheer curiosity, I integrated my own answer with your original code and F.J.'s solutions to make a comparative performance test.
It seems that your solution is the fastest of them all. My solution check all possible elements of the controls tuple, so it will be slower as the size of the tuple increases.
Here is the code:
and here is the output on my system:
HTH! :)
如果不存在这样的控件,则抛出IndexError。
有点深奥,但不需要尝试/例外:
Throws IndexError if no such control exists.
A bit esoteric, but without requiring try/except: