停止列表选择? [英] Stopping list selection?

查看:54
本文介绍了停止列表选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有一个元组的订单列表:

Imagine that I have an order list of tuples:

s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)]

给定参数X,我要选择所有第一个元素等于或大于X的元组,直到但不包括具有-1作为第二个元素的第一个元组.

Given a parameter X, I want to select all the tuples that have a first element equal or greater than X up to but not including the first tuple that has -1 as the second element.

例如,如果X = 3,我要选择列表[(3,0), (4,0)]

For example, if X = 3, I want to select the list [(3,0), (4,0)]

我的一个主意是: 使用

One idea I had is: Get the cut-off key with

E = min (x [0] for x in s if (x [0] >= X) and (x [1] == -1) )

然后使用XE之间的键选择元素:

Then select elements with keys between the X and E:

R = [x for x in s if X <= x [0] < E]

这给了我我在R语言中想要的东西,但是它看起来效率很低,涉及两次表扫描.我可以在for循环中执行此操作,丢弃键过小的元组,并在遇到第一个阻塞元组时 break .但是与列表选择相比,像狗一样奔跑.

That gives me what I want in R, but it seems really inefficient, involving two table scans. I could do it in a for loop, discarding tuples with keys too small, and break when I hit the first blocking tuple. But for runs like a dog compared to list selection.

是否有一种超高效的python式(2.7)方法?

Is there a super-efficient, python-esque (2.7) way of doing this?

推荐答案

您可以简单地将列表中的元组过滤为生成器表达式,然后在获取第一个元组而第二个得到第二个元组时就停止从生成器表达式中获取值元素是-1,就像这样

You can simply filter the tuples from the list as a generator expression and then you can stop taking the values from the generator expression when you get the first tuple whose second element is -1, like this

>>> s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)]
>>> from itertools import takewhile
>>> X = 3
>>> list(takewhile(lambda x: x[1] != -1, (item for item in s if item[0] >= X)))
[(3, 0), (4, 0)]

在这里,生成器表达式(item for item in s if item[0] >= X)将按需给出一个或多个值(它们不会一次全部生成,因此我们在这里保存了内存),这些值大于或等于X.

Here, the generator expression, (item for item in s if item[0] >= X) will give values one-by-one, on demand, (they are not generated all at once, so we save memory here) which are greater than or equal to X.

然后,我们从该生成器表达式中获取值,直到找到具有第二个元素不等于-1的元组,并使用

Then, we take values from that generator expression, only till we find a tuple whose second element is not equal to -1, with itertools.takewhile.

这篇关于停止列表选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆