在 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);
我听说 Python 的语法比 C# 更简洁(因此效率更高),那么如何使用 Python 中的可迭代对象以相同或更少的代码实现相同的效果?
注意:如果不需要的话,我不想将可迭代物化为列表(Any
, Count
, First
).
以下 Python 行应该与您所拥有的相同(假设func
, or 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]
参考:
- 列表推导式 http://docs.python.org/tutorial/datastructures.html#list-comprehensions
- 生成器表达式 http://docs.python.org/tutorial/classes.html#generator-expressions
- any()内置功能 http://docs.python.org/library/functions.html#any
- sum()内置功能 http://docs.python.org/library/functions.html#sum
- set type http://docs.python.org/library/stdtypes.html#set-types-set-frozenset
注意我改名了lambda
to func
since lambda
是Python中的一个关键字,我重命名为except
to except_
为了同样的原因。
请注意,您还可以使用map() http://docs.python.org/library/functions.html#map而不是推导式/生成器,但它通常被认为可读性较差。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)