Fla*_*ien 8 python iterator functional-programming
在C#中,使用LINQ,如果我有en枚举enumerable,我可以这样做:
// a: Does the enumerable contain an item that satisfies the lambda?
bool contains = enumerable.Any(lambda);
// b: How many items satisfy the lambda?
int count = enumerable.Count(lambda);
// c: Return an enumerable that contains only distinct elements according to my custom comparer
var distinct = enumerable.Distinct(comparer);
// d: Return the first element that satisfies the lambda, or throws an exception if none
var element = enumerable.First(lambda);
// e: Returns an enumerable containing all the elements except those
// that are also in 'other', equality being defined by my comparer
var except = enumerable.Except(other, comparer);
Run Code Online (Sandbox Code Playgroud)
我听说Python有比C#更简洁的语法(因此效率更高),所以我用Python中的迭代实现相同的代码,或者更少的代码?
注意:如果我不需要(Any,Count,First),我不想将iterable实现为列表.
And*_*ark 16
以下 Python 行应该与您所拥有的相同(假设func或lambda在您的代码中,返回一个布尔值):
# Any
contains = any(func(x) for x in enumerable)
# Count
count = sum(func(x) for x in enumerable)
# Distinct: since we are using a custom comparer here, we need a loop to keep
# track of what has been seen already
distinct = []
seen = set()
for x in enumerable:
comp = comparer(x)
if not comp in seen:
seen.add(comp)
distinct.append(x)
# First
element = next(iter(enumerable))
# Except
except_ = [x for x in enumerable if not comparer(x) in other]
Run Code Online (Sandbox Code Playgroud)
参考:
请注意,我改名lambda到func,因为lambda是一个Python关键字,我改名except,以except_出于同样的原因。
请注意,您也可以使用map()推导式/生成器代替,但通常认为它的可读性较差。
我们有生成器表达式和各种用于在可迭代对象上表达任意条件的函数。
any(some_function(e) for e in iterable)
sum(1 for e in iterable if some_function(e))
set(iterable)
next(iterable)
(e for e in iterable if not comparer(e) in other)
Run Code Online (Sandbox Code Playgroud)
大致对应于您使用惯用 Python 编写示例的方式。