我想从符合条件的列表中获取第一项.重要的是,生成的方法不会处理整个列表,这可能非常大.例如,以下功能就足够了:
def first(the_iterable, condition = lambda x: True):
for i in the_iterable:
if condition(i):
return i
Run Code Online (Sandbox Code Playgroud)
这个函数可以用这样的东西:
>>> first(range(10))
0
>>> first(range(10), lambda i: i > 3)
4
Run Code Online (Sandbox Code Playgroud)
但是,我想不出一个好的内置/单线来让我这样做.如果我不需要,我不特别想复制这个功能.是否有内置方法可以使第一个项目符合条件?
我不知道是否有一个原因,有没有first(iterable)在Python内置的功能,有点类似于any(iterable)和all(iterable)(可能一STDLIB模块中夹着地方,但我没有看到它itertools).first将执行短路发生器评估,以便可以避免不必要的(和可能无限数量的)操作; 即
def identity(item):
return item
def first(iterable, predicate=identity):
for item in iterable:
if predicate(item):
return item
raise ValueError('No satisfactory value found')
Run Code Online (Sandbox Code Playgroud)
这样你可以表达如下内容:
denominators = (2, 3, 4, 5)
lcd = first(i for i in itertools.count(1)
if all(i % denominators == 0 for denominator in denominators))
Run Code Online (Sandbox Code Playgroud)
很明显,list(generator)[0]在这种情况下你不能这样做,因为发生器不会终止.
或者,如果你有一堆正则表达式匹配(当它们都具有相同的groupdict接口时很有用):
match = first(regex.match(big_text) for regex in regexes)
Run Code Online (Sandbox Code Playgroud)
通过避免list(generator)[0]和短路匹配来节省大量不必要的处理.
如何在满足特定标准的序列中找到对象?
列表理解和过滤器遍历整个列表.是手工制作的唯一选择吗?
mylist = [10, 2, 20, 5, 50]
find(mylist, lambda x:x>10) # Returns 20
Run Code Online (Sandbox Code Playgroud) 可能重复:
Python:查找与谓词匹配的序列中的第一个元素
Python标准库中是否有更高阶的函数来封装以下控制流模式?
>>> def find(pred, coll):
... for x in coll:
... if pred(x):
... return x
...
>>> find(lambda n : n % 2 == 0, [3, 5, 8, 9, 6])
8
>>> find(lambda n : n % 2 == 0, [3, 5, 7, 9, 6])
6
>>> find(lambda n : n % 2 == 0, [3, 5, 7, 9, 1])
Run Code Online (Sandbox Code Playgroud) 我有一个清单
list_a = [(1, 2), (2, 3), (4, 5)]
Run Code Online (Sandbox Code Playgroud)
现在使用这个列表我想找到一个具有最后值3的元素,任何简短的方法来实现这一点?它应该回来(2,3)
给出清单:
li = ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
Run Code Online (Sandbox Code Playgroud)
如何找到包含字符串的(第一个)索引amp?注意amp包含单词example.
仅供参考,这有效: li.index("example")
但这不是: li.index("amp")
考虑以下类:
class MyClass():
def __init__(self,attr):
self.attr=attr
Run Code Online (Sandbox Code Playgroud)
和 MyClass 对象列表:
myList=[MyClass(1),MyClass(2),MyClass(3)]
Run Code Online (Sandbox Code Playgroud)
属性值是唯一的。要获取具有特定值的对象的引用(例如:2),我使用了
[i for i in myList if i.attr==2][0]
Run Code Online (Sandbox Code Playgroud)
或者
myList[[i.attr for i in myList].index(2)]
Run Code Online (Sandbox Code Playgroud)
做到这一点的最佳方法是什么,是否有更好的解决方案?(如果可以,因为我是 Python 初学者,请回答不同解决方案的优缺点,将不胜感激)。(Rq:这个例子很简单,列表可以更大,对象更复杂)
谢谢你的回答。