用于查询 Python 列表中哪个元素最先出现的语法糖
我有一个包含许多元素的列表。
我关心它的两个元素,a
和 b
。
我不知道列表的顺序,也不想对其进行排序。
是否有一个很好的单行代码,如果 a
出现在 b
之前,则返回 True,否则返回 false?
I have a list of many elements.
I care about two of its elements, a
and b
.
I don't know the order of the list, nor do I want to sort it.
Is there a nice one-liner that will return True
if a
occurs before b
and false otherwise?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了多样性,您还可以:
如果
a == b
,则为True
。如果您知道a != b
,In the interests of diversity, you could also:
This will be
True
ifa == b
. If you know thata != b
,编辑:重写以检查更多情况,
好,所以这个问题需要更多的工作。马克·拜尔斯 (Mark Byers) 是完全正确的,因为我的第一个测试仅涵盖结果为
True
的情况。这尤其重要,因为我们需要其他解决方案的异常处理程序。因此,我更详细地介绍了:结果:
因此,jcollado 方法的效率增益大部分被异常处理程序的成本所消耗(特别是如果它触发)。所有三种解决方案都有一半的时间获胜(或与获胜者并列),因此很难说哪种方法最适合您的实际数据。也许您可能想要选择最容易阅读的一本。
Edit: Rewritten to check more cases
OK, so this problem needs a bit more work. Mark Byers is completely right in that my first test only covered cases where the result would be
True
. This is especially relevant because we need exception handlers for the other solutions. So I've gone into a bit more detail:results in:
So the efficiency gain from jcollado's method is mostly eaten up by the cost of the exception handler (expecially if it triggers). All three solutions win (or tie with the winner) half of the time, so which method works best on your actual data is hard to say. Perhaps you might want to go with the one that's easiest to read.
您可以使用
list.index
:这当然假设这两个项目都存在于列表中。
You can use
list.index
:This of course assumes that both items are present in the list.
Mark Byers 的响应效果很好,但如果列表很长并且两个元素都接近末尾,则效率不会很高。
要仅遍历列表一次,您可以使用以下命令:
这是所需的单行代码,但无论如何您都需要捕获
ValueError
异常。Response from Mark Byers works fine, but it won't be very efficient if list is long and both elements are close to the end.
To traverse the list just once, you can use this:
This is a one-liner as required, but you'll need to capture
ValueError
exception anyway.