Python有类似C#的Enumerable.Aggregate的方法吗?

3 投票
3 回答
1629 浏览
提问于 2025-04-17 03:17

在C#中,如果我有一组字符串,想把它们变成一个用逗号分隔的字符串(而且开头和结尾不要多余的符号),我可以这样做:

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

我可以这样做:

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

但是这样做感觉有点笨拙。Python有没有更优雅的方法来实现同样的效果呢?

3 个回答

0

你可以这样做:

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

我建议你查一下“python 列表推导式”(上面那个 [ ... for ... ] 部分),这样可以获得更多信息。

5

在C#中,有个叫做Enumerable.Aggregate的方法,而在Python里,有个类似的内置方法叫做"reduce"。

举个例子,

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

这个方法可以计算((((1+2)+3)+4)+5),结果是15。

这意味着你可以用下面的方式来实现相同的效果:

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

或者用

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

在你的情况下,使用', '.join会更好,正如其他人所建议的,因为Python的字符串是不可变的。

为了完整起见,C#中的Enumerable.Select方法在Python中对应的是"map"。

现在如果有人问你,你可以说你知道MapReduce啦 :)

7

使用 str.join 方法:

result = ', '.join(iterable)

如果集合中的所有项目不是字符串,你可以使用 map 或者生成器表达式:

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

撰写回答