简体   繁体   English

python是否等效于C#的Enumerable.Aggregate?

[英]Does python have an equivalent to C#'s Enumerable.Aggregate?

In C#, if I have a collection of strings, and I want to get a comma-separated string representing of the collection (without extraneous comments at the beginning or end), I can do this: 在C#中,如果我有一个字符串集合,并且我想获得一个用逗号分隔的字符串来表示该集合(在开头或结尾处没有多余的注释),则可以这样做:

string result = collection.Aggregate((s1, s2) => String.Format("{0}, {1}", s1, s2));

I could do something like 我可以做类似的事情

result = collection[0]
for string in collection[1:]:
    result = "{0}, {1}".format(result, string)

But this feels like a cludge. 但这感觉就像是一堆杂物。 Does python have an elegant way to accomplish the same thing? python是否有一种优雅的方式来完成同一件事?

Use str.join : 使用str.join

result = ', '.join(iterable)

If not all the items in the collection are strings, you can use map or a generator expression: 如果集合中的所有项目都不都是字符串,则可以使用map或生成器表达式:

result = ', '.join(str(item) for item in iterable)

The Equivalent of the C# Enumerable.Aggregate method is pythons built in "reduce" method. C#Enumerable.Aggregate方法的等效项是在“ reduce”方法中构建的python。 For example, 例如,

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 

Calculates ((((1+2)+3)+4)+5). 计算(((((1 + 2)+3)+4)+5)。 which is 15 那是15

This means you could achieve the same with 这意味着您可以通过

result = reduce(lambda s1, s2: "{0}, {1}".format(s1, s2), collection)

Or with 或搭配

result = reduce(lambda s1, s2: s1 + ", " + s2, collection)

In your Case it would be better to use ', '.join as others have suggested because of pythons immutable strings. 在您的情况下,最好使用', '.join因为其他人建议这样做,因为python是不可变的字符串。

For completeness the C# Enumerable.Select method in python is "map". 为了完整起见,Python中的C#Enumerable.Select方法是“ map”。

Now if anyone asks you can say you know MapReduce :) 现在,如果有人问您可以说您知道MapReduce :)

You could do something like: 您可以执行以下操作:

> l = [ 1, 3, 5, 7]
> s = ", ".join( [ str(i) for i in l ] )
> print s
1, 3, 5, 7

I suggest looking up "python list comprehensions" (the [ ... for ... ] in the above) for more info. 我建议查找“ python列表推导”(以上的[... ... ...])以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM